Six degrees of web separation Six degrees of separation is the theory that everyone and everything is six or fewer steps away, by way of introduction, from any other person in the world.

Your challenge here is to write a program which crawls to find out what is exactly 6 links away but connected back to the starting URL through a series of links.

For example if your program is given a starting url of http://vimeo.com it would then potentially (this is a made up example) crawl to:

http://www.abc.com links to ->
http://www.widgets.com links to ->
http://www.gadgets.net links to ->
http://www.techcrunch.com links to ->
https://twitter.com/techcrunch links to ->
http://www.youtube.com/user/techcrunch (finish as we are now 6 links away from the starting URL.)

Rules:

You can choose your own starting URL.
Any programming language can be used.
You most obey sites robots.txt files and not crawl any areas sites disallow.
Each step must be a new URL from the one you are currently on.
URLS should only be visited once per crawl.
You must output the starting URL and each link followed in sequence.

Winner:

This is a popularity contest so the solution with the most up-votes wins.

Java, 8623 bytes

It isn't perfect. It has some issues connecting to some URLs and fails to parse the robots.txt properly. However, it's a start.

package info.varden.codegolf.sixdegreeslink;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    private static HashMap<String, String> entities = new HashMap<>();
    private static HashMap<String, ArrayList<String>> robotstxts = new HashMap<>();

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        String init = "";
        for (String s : args) {
            init += s + "%20";
        }
        init = init.substring(0, init.length() - 3);
        try {
            System.out.println("Resolving entites (step 1 of 3)...");
            entities.putAll(getEntitiesFromEnt("http://www.w3.org/TR/html4/HTMLlat1.ent"));
            System.out.println("Resolving entites (step 2 of 3)...");
            entities.putAll(getEntitiesFromEnt("http://www.w3.org/TR/html4/HTMLsymbol.ent"));
            System.out.println("Resolving entites (step 3 of 3)...");
            entities.putAll(getEntitiesFromEnt("http://www.w3.org/TR/html4/HTMLspecial.ent"));
            System.out.println(entities.size() + " entites resolved.\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Starting search from: " + init + "\n");
        IterationInfo initInfo = new IterationInfo();
        IterationInfo info = initInfo;
        try {
            initInfo.scanLink = init;
            initInfo.links.add(init);
            initInfo.domains.add(getDomain(init));
            info = getSixStepsRecursive(initInfo);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        long diffTime = System.currentTimeMillis() - startTime;
        long second = (diffTime / 1000) % 60;
        long minute = (diffTime / (1000 * 60)) % 60;
        long hour = (diffTime / (1000 * 60 * 60)) % 24;
        diffTime = diffTime % 1000;

        String time = String.format("%02d:%02d:%02d.%d", hour, minute, second, diffTime);
        System.out.println("\nCompleted in " + time);
        System.out.println("\nRESULTS:");
        if (info.success) {
            for (int i = 0; i < info.links.size(); i++) {
                System.out.println(info.links.get(i));
            }
        } else {
            System.out.println("Can't find six degrees step separation!");
        }
    }

    private static IterationInfo getSixStepsRecursive(IterationInfo info) {
        IterationInfo returnInfo = info;
        String[] urls = new String[0];
        try {
            String content = downloadString(info.scanLink);
            content = content.replace("\t", " ").replace("\r", " ").replace("\n", " ");
            while (content.contains("  ")) content = content.replace("  ", " ");
            urls = content.split("\\Q<a href=\"\\E");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        for (int i = 1; i < urls.length; i++) {
            try {
                if (info.iteration == 6) {
                    returnInfo.success = true;
                    return returnInfo;
                }
                returnInfo = info;
                urls[i] = stripHTMLEntities(urls[i].split("\"")[0]);
                if (urls[i].startsWith("//"))
                    urls[i] = "http:" + urls[i];
                if (!urls[i].startsWith("http://") && !urls[i].startsWith("https://")) {
                    System.out.println("Iter " + info.iteration + " - URL failed: Relative or non-HTTP link (" + urls[i] + ")");
                    continue;
                }
                if (!canGetRobotsTxt(urls[i])) {
                    System.out.println("Iter " + info.iteration + " - URL failed: Blocked by robots.txt (" + urls[i] + ")");
                    continue;
                }
                if (returnInfo.links.contains(urls[i])) {
                    System.out.println("Iter " + info.iteration + " - URL failed: Exact link already passed (" + urls[i] + ")");
                    continue;
                }
                if (returnInfo.domains.contains(getDomain(urls[i]))) {
                    System.out.println("Iter " + info.iteration + " - URL failed: Domain already passed (" + getDomain(urls[i]) + ") (" + urls[i] + ")");
                    continue;
                }

                System.out.println("Iter " + info.iteration + " - URL valid: Distict domain (" + getDomain(urls[i]) + ") (" + urls[i] + ")");
                returnInfo.links.add(urls[i]);
                returnInfo.domains.add(getDomain(urls[i]));
                returnInfo.iteration = info.iteration + 1;
                returnInfo.scanLink = urls[i];

                returnInfo = getSixStepsRecursive(returnInfo);
                if (returnInfo.success) {
                    return returnInfo;
                }
            } catch (Exception ex) {
            }
        }
        return returnInfo;

    }

    private static boolean canGetRobotsTxt(String url) {
        try {
            URI cur = new URI(url);
            if (!robotstxts.containsKey(cur.getHost())) {
                String rtxt = downloadString("http://" + cur.getHost() + "/robots.txt");
                String[] lines = rtxt.split("\n");
                ArrayList<String> ar = new ArrayList<>();
                for (String line : lines) {
                    if (line.endsWith("\r"))
                        line = line.substring(0, line.length() - 1);
                    if (line.toLowerCase().startsWith("disallow: ")) {
                        line = line.substring(10);
                        ar.add(line);
                    } else if (line.toLowerCase().startsWith("allow: ")) {
                        line = line.substring(7);
                        ar.remove(line);
                    }
                }
                robotstxts.put(cur.getHost(), ar);
            }
            ArrayList<String> a = robotstxts.get(cur.getHost());
            for (String s : a) {
                String[] sw = s.split("\\Q*\\E");
                String s2 = "^i";
                for (String s3 : sw) {
                    s2 += "\\Q" + s3 + "\\E(.+)";
                }
                s2 = s2.substring(0, s2.length() - 4);
                Pattern p = Pattern.compile(s2);
                Matcher m = p.matcher(cur.getPath());
                if (m.find()) {
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            return true;
        }
    }

    private static HashMap<String, String> getEntitiesFromEnt(String url) throws Exception {
        HashMap<String, String> e = new HashMap<>();
        String ent = downloadString(url);
        while (ent.contains("  ")) ent = ent.replace("  ", " ");
        String[] lines = ent.split("\n");
        for (String line : lines) {
            if (line.startsWith("<!ENTITY")) {
                String[] f = line.split(" ");
                e.put("&" + f[1] + ";", f[3].substring(1, f[3].length() - 1));
            }
        }
        return e;
    }

    private static String downloadString(String url) throws Exception {
        URL cur = new URL(url);
        URLConnection conn = cur.openConnection();
        conn.setRequestProperty("User-Agent", "URLConnection/1.7 (Any system) VardenCG/3.0");
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String content = "", line;
        while ((line = in.readLine()) != null) content += line + "\n";
        in.close();
        return content;
    }

    private static String stripHTMLEntities(String html) {
        for (Entry<String, String> e : entities.entrySet())
            html = html.replace(e.getKey(), e.getValue());
        Pattern ep = Pattern.compile("&#(\\d+);");
        Matcher m = ep.matcher(html);
        while (m.find()) {
            if (!m.group(1).equals("38"))
                html = html.replace("&#" + m.group(1) + ";", String.valueOf((char)Integer.parseInt(m.group(1))));
        }
        Pattern ep1 = Pattern.compile("&(x|X)([\\da-fA-F]+);");
        Matcher m2 = ep1.matcher(html);
        while (m2.find()) {
            if (!m.group(1).equals("26")) {
                html = html.replace("&x" + m2.group(2) + ";", String.valueOf((char)Integer.parseInt(m2.group(2), 16)));
                html = html.replace("&X" + m2.group(2) + ";", String.valueOf((char)Integer.parseInt(m2.group(2), 16)));
            }
        }
        html = html.replace("&#38;", "\0").replace("&x26;", "\0").replace("&X26;", "\0").replace("\0", "&");
        return html;
    }

    private static String getDomain(String url) throws URISyntaxException {
        URI uri = new URI(url);
        String host = uri.getHost().toLowerCase();
        String[] subDomainTree = host.split("\\.");
        String[] commonSLs = {"ac", "co", "com", "gov", "ltd", "me", "net", "org"};
        boolean isCommonSL = false;
        try {
            String secondLevel = subDomainTree[subDomainTree.length - 2];
            for (String sl : commonSLs) {
                if (sl.equals(secondLevel)) {
                    isCommonSL = true;
                }
            }
        } catch (ArrayIndexOutOfBoundsException ex) {
            return host;
        }
        try {
            if (isCommonSL) {
                return subDomainTree[subDomainTree.length - 3] + "." +
                        subDomainTree[subDomainTree.length - 2] + "." +
                        subDomainTree[subDomainTree.length - 1];
            } else {
                return subDomainTree[subDomainTree.length - 2] + "." +
                        subDomainTree[subDomainTree.length - 1];
            }
        } catch (ArrayIndexOutOfBoundsException ex) {
            return subDomainTree[subDomainTree.length - 2] + "." +
                    subDomainTree[subDomainTree.length - 1];
        }
    }

    private static class IterationInfo {
        public ArrayList<String> domains = new ArrayList<>();
        public ArrayList<String> links = new ArrayList<>();
        public String scanLink = "";
        public int iteration = 1;
        public boolean success = false;
    }

}

Parameter used: http://codegolf.stackexchange.com/

Output: http://pastebin.no/34cd (Had to post on other site because it was too big for codegolf)

There's a lot of stuff going on here.

First of all, I have to parse HTML entities like &em; &39; and &x2F;. The named entities have to be translated, I do that by downloading the definitions from W3C.

I also need to figure out the host of the URL, taking into account common second level domains like co, edu etc. (.co.uk, .edu.uk, ...)

Then I need to parse robots.txt.

I don't have time to write more now, but oh well, there's my contribution.

-- bilde2910


Sum the array times n, except the last I've been posting relatively hard challenges recently, so here goes an easy one.
Task
Given an array \$A\$ and a number \$n\$, calculate the sum of all numbers of \$A\$ multiplied by \$n\$, except the last one. All numbers (the elements of \$A\$ and the value of \$n\$) are positive integers, and \$A\$ is non-empty. Shortest code in bytes wins.
I have a 3-byte J solution. Can you find it (or beat it in a different language)?

Test cases
A           N   Ans   Explanation
3 1 4 1 5   10  95    (3+1+4+1)*10+5
3 1 4 1 5   1   14    (3+1+4+1)*1+5
1           999 1     1

J, 3 bytes
That was fun to find.
&+/

Try it online!
How it works
10 (&+/) 3 1 4 1 5 will bind 10 as an argument of + as 10&+, one verb that gets inserted between the elements of the list by /. So we have: 3 (10&+) 1 (10&+) 4 (10&+) 1 (10&+) 5. Now x n&v y means that y gets applied to n&v for x times. With J's right to left evaluation we get: to 5 add 1 times 10, add 4 times 10, add 1 times 10, add 3 times 10. A challenge made for J's stranger parts. :-) And because + is commutative, +&/ would also be a valid solution.


Overlapping Polyglots Unlike many C&R challenges, this does not require a separate robbers post; the goal of the robbers is to crack the previous answer and then post a new one as a cop.

As answerers, you will write a series of polyglots that look like this (each column is a language, and each entry is the output of the answer in that language):

Language:  1  2  3  4  5  6  7  8  ...
Answer 1:  0  1  2
Answer 2:     1  2  3
Answer 3:        2  3  4
Answer 4:           3  4  5
Answer 5:              4  5  6
Answer 6:                 5  6  7
...

(blank spaces mean that no behavior is required in that case).

Each answer should work in 3 languages and print 3 different consecutive numbers which are each one more than the numbers printed by the previous answer (the first answer prints 0, 1, and 2). Each answer uses two languages from the previous submission, and a third new language. The answerer should try to obfuscate what this third language is.

To post a new answer, you should:

Crack the most recent answer by finding what its third language is.
Preferably, add an explanation for your crack and notify the poster of the answer. Once your submission has been cracked, you should preferably add an explanation as well.
Write a polyglot consisting of this answer's second and third languages, along with another language of your choice. Reveal your first two languages, but do not reveal your new one. It will be the next poster's goal to find this language (or any other language in which it works), so you should try to obfuscate it.

Specifications

The criteria for a valid programming language are the same as those of The Programming Language Quiz, Mark II - Cops:

  It has an English Wikipedia article, an esolangs article or a Rosetta Code article at the time this challenge was posted, or is on Try It Online!. Having an interpreter linked in any of these pages makes that interpreter completely legal.
  It must satisfy our rules on what constitutes a programming language.
  It must have a free interpreter (as in beer). Free here means that anyone can use the program without having to pay to do so.

Each answer must run in less than a minute on a reasonable PC.
You can reuse programming languages, but there must be at least two answers in between (so an individual answer cannot reuse a language).
Cracking a submission consists of finding any programming language that prints the correct result, not just the intended one. If a submission is run in any language that was not declared or found to work, there are no requirements to do anything.
You may not post twice (or more) in a row.

Winning Criterion

The winning answer is whichever answer took to most time to be cracked. The challenge will  never end, so it is always possible for the winning answer to change.

Hexagony, Klein (101) and ???

  xx={puts/}
gets87!@xx=p

main\

>9.*5,6v

This prints 7 in Hexagony, 8 in Klein (101), and 9 in ???.

The 9 does not work if a newline is added at the end of the code. Be careful if you're testing locally.

Edit: Being live for 20 hours is already a record, so I'll give some hints from now on. (Also because the language in question is IMO not yet well-known.)

Hints

"The 9 does not work if a newline is added at the end" is very significant, as well as the first two spaces (which are ignored by both Hexagony and Klein).
The language is on TIO.
The first two spaces make the program jump to the last line. (It's not a 2D language.)
There's no explicit output command, and the v command ends the program.

Explanation (cracked post)

In the source code

abcd={} -- a gaffe avoiding tactic in C++/C#
abcd[!1]=   1+2+3+4+5+6+7+8+9+10+11+12+13+17!
print(abcd[0>1+2+3 and 4+8+6<0-0]//35)
if 0>1 then a.next=';' en\
                    >1+6.@.@

The relevant instructions in Klein (101) are:

IP->.....................^...........IP->/
.........................|...................
.........................8
.........................\<-.............IP<-
                         @

Klein is fungelike 2D language where crossing the boundary of code area (which is a square) depends on the Klein topology. / and \ are mirrors.

The IP starts at upper left corner facing right. It meets a mirror towards the top boundary, and re-enters the code area on the right side as shown above. Then it hits the mirror again, 8 is pushed, and then (after passing through the boundary several times) stops at @. Then the content of the stack is printed to stdout, which is single 8.


Find the optimal set of weights to add to a certain set of weights In this challenge, you will recieve a comma-separated list of weights as input, such as

1,3,4,7,8,11

And you must output the smallest amount of weights that can add to that set. For example, the output for this set would be

1,3,7

Because you could represent all of those weights with just those three:

1     = 1
3     = 3
1+3   = 4
7     = 7
1+7   = 8
1+3+7 = 11

There may be more than one solution. For example, your solution for the input 1,2 could be 1,1 or 1,2. As long as it finds the minimum amount of weights that can represent the input set, it is a valid solution.

Weights may not be used more than once. If you need to use one twice, you must output it twice. For example, 2,3 is not a valid solution for 2,3,5,7 because you can't use the 2 twice for 2+2+3=7.

Input is guaranteed not to have duplicated numbers.

This is code-golf so shortest code by character count wins.

Network access is forbidden (so none of your "clever" wget solutions @JohannesKuhn cough cough) ;)

Simpleest cases:

1,5,6,9,10,14,15               => 1,5,9
7,14,15,21,22,29               => 7,14,15
4,5,6,7,9,10,11,12,13,15,16,18 => 4,5,6,7
2,3,5,7                        => 2,2,3 or 2,3,7

And some trickier ones:

10,16,19,23,26,27,30,37,41,43,44,46,50,53,57,60,61,64,68,71,77,80,84,87
  => 3,7,16,27,34
20,30,36,50,56,63,66,73,79,86
  => 7,13,23,43
27,35,44,46,51,53,55,60,63,64,68,69,72,77,79,81,86,88,90,95,97,105,106,114,123,132
  => 9,18,26,37,42

Mathematica 80 75

Update: See at bottom an update on Doorknob's challenging last test, added on Nov.5

This passes all but the last test. However, it does not attempt to use a digit more than once.  And it only searches from solutions that are subsets of the larger data set.

The function generates all of the subsets of the input data set and then tests which subsets can be used to construct the complete set. After the viable subsets are found, it chooses the smallest sets.

s=Subsets
f@i_:=GatherBy[Select[s@i,Complement[i, Total /@ s@#]=={}&],Length]〚1〛

Tests

f[{1, 3, 4, 7, 8, 11}]

  {{1, 3, 7}}

f[{1, 5, 6, 9, 10, 14, 15}]

  {{1, 5, 9}}

f[{7, 14, 15, 21, 22, 29}]

  {{7, 14, 15}}

f[{4, 5, 6, 7, 9, 10, 11, 12, 13, 15, 16, 18}]

  {{4, 5, 6, 7}}

f[{2, 3, 5, 7}]

  {{2, 3, 5}, {2, 3, 7}}

Update

Below I'll provide an initial analysis that may help get started toward a solution.

The data:

data = {10, 16, 19, 23, 26, 27, 30, 37, 41, 43, 44, 46, 50, 53, 57, 60, 61, 64, 68, 71, 77, 80, 84, 87};

Differently from the earlier approach, we want to consider, in the solution set, numbers that do NOT appear in the data set.

The approach makes use of absolute differences between pairs of numbers in the data set.

g[d_] := DeleteCases[Reverse@SortBy[Tally[Union[Sort /@ Tuples[d, {2}]] /. {a_, b_} :> Abs[a - b]], Last], {0, _}]

Let's look at the number of times each difference appears; we'll only grab the first 8 cases, starting from the most common difference].

g[data][[1;;8]]

  {{7, 14}, {27, 13}, {34, 12}, {3, 11}, {20, 10}, {16, 10}, {4,
    10}, {11, 9}}

14 pairs differed by 7; 13 pairs differed by 27, and so on.

Now let's test subsets starting with {difference1},{difference1, difference2}, and so on, until we can hopefully account for all the original elements in the data set.

h reveals those numbers from the original set that cannot be constructed by composing sums from the subset.

h[t_] := Complement[data, Total /@ Subsets@t]

By the fifth try, there are still 10 elements that cannot be formed from {7, 27, 34, 3, 20}:

h[{7, 27, 34, 3, 20}]

  {16, 19, 26, 43, 46, 53, 60, 77, 80, 87}

But on the next try, all numbers of the data set are accounted for:

h[{7, 27, 34, 3, 20, 16}]

  {}

This is still not as economical as {3,7,16,27,34}, but it's close.

There are still some additional things to take into account.

If 1 is in the data set, it will be required in the solution set.
There may well be some "loners" in the original set that cannot be composed from the most common differences. These would need to be included apart from the difference tests.

These are more issues than I can handle at the moment. But I hope it sheds some light on this very interesting challenge.


Classify Quadrilaterals | Help me with my math exam! Help! My math exam is coming up soon and I didn't study! 1 Part of the exam is to classify a quadrilateral given its vertex coordinates, which I, unfortunately, do not know how to do. 2

So, your challenge is to write a program to do this for me so I don't fail!

Challenge

Given four vertices such that no three of them are colinear, determine the most specific classification of the quadrilateral formed by those four vertices.

What I mean by "most specific classification" is that even though all squares are rectangles, if the shape is a square, you should indicate that it is a square and not indicate that it is a rectangle.

Input

Input will be given as four (x, y) coordinates. You may take these as a list of length 4 of lists/tuples of length 2. Alternatively, you can take input as a list of the x-coordinates and a list of the respective y-coordinates.

For example, if my shape has vertices at points (0, 0), (5, 0), (6, 1), and (1, 1), you may choose to take input in either of the following formats or something similar:

[(0, 0), (5, 0), (6, 1), (1, 1)]
([0, 5, 6, 1], [0, 0, 1, 1])

You may assume that the quadrilateral is not self-intersecting and that the points are given in the correct order (that is, two consecutive points in the input will be connected by a line segment in the quadrilateral).

Output

You will need a unique output for each of the following classes of quadrilaterals:

Square
Rectangle
Rhombus
Parallelogram
Trapezoid/Trapezium
Kite
Quadrilateral

This could be the exact name itself, a character, an integer, etc.

Rules

Standard Loopholes Apply
If your programming language has a built-in that will perform this exact task, that built-in is not allowed.
Built-ins for finding the distance between two points are allowed.
Built-ins for finding the angle between two lines are allowed.

At this point, if you know all of the terms, you are ready to start programming! (Test Cases are at the end)

Terminology

This section is for anyone who needs clarification on the definitions of the different shapes.

Square

A quadrilateral is a square if and only if all 4 of its sides are equal in length and every pair of adjacent sides is perpendicular (that is, it is both a rectangle and a rhombus).

Rectangle

A quadrilateral is a rectangle if and only if every pair of adjacent sides is perpendicular.

Rhombus

A quadrilateral is a rhombus if and only if all 4 of its sides are equal.

Parallelogram

A quadrilateral is a parallelogram if and only if each pair of opposite sides is parallel and each pair of opposite angles is equal. Both of these conditions imply each other so you only need to check for one of them.

Trapezoid/Trapezium

A quadrilateral is a trapezoid/trapezium if and only if it has at least one pair of parallel sides.

Kite

A quadrilateral is a kite if two opposite pairs of adjacent sides are equal in length; that is, two of its adjacent sides are equal and the other two are also equal.

Test Cases

input as (x, y) * 4 -> full name
[(0, 0), (1, 0), (1, 1), (0, 1)] -> square
[(0, 0), (1, 1), (-1, 3), (-2, 2)] -> rectangle
[(0, 0), (5, 0), (8, 4), (3, 4)] -> rhombus
[(0, 0), (5, 0), (6, 1), (1, 1)] -> parallelogram
[(0, 0), (4, 0), (3, 1), (1, 1)] -> trapezoid/trapezium
[(0, 0), (1, 1), (0, 3), (-1, 1)] -> kite
[(0, 0), (2, 0), (4, 4), (0, 1)] -> quadrilateral

Links (Desmos Graphing Calculator)

Here are links to visualizations of each of the test cases.

Square
Rectangle
Rhombus
Parallelogram
Trapezoid/Trapezium
Kite
Quadrilateral

Winning Criteria

I can't bring a computer into the exam obviously, so I need you to write the shortest code possible so I can memorize it. I need to write it into the margins and run it using TryItOfflineTM so to fit it into the margins your program needs to be as small as possible!

1 Of course I actually did :P
2 Of course I actually do :P

APL (Dyalog), 104 89 80 82 81 79 78 bytes

⍙←{⍵⍺⍺1⌽⍵}
⎕←(|x){⍵≡2⌽⍵:≡⍙¨0⍺⍵⋄2 4=+/1=2|+⍙↑⍵(=⍙⍺)}2|1+-⍙(12○x←-⍙⎕+.×1 0J1)÷○1

Try it online!

Input/Output
Takes a 4×2 matrix of coordinates as input
Outputs

1 1 1 for Square
1 1 0 for Rhombus
1 0 1 for Rectangle
1 0 0 for Parallelogram
1 0 for Kite
0 1 for Trapezium
0 0 for Quadrilateral

Algorithm
First, find all 4 side lengths and angles of the quadrilateral
If both pairs of opposite angles are equal (OA), then the shape is some kind of parallelogram. Determine if all side lengths are equal (AS, Adjacent Sides) and if all angles are equal (AA).
+--------+----------------+----------------+
|        |       AA       |      ~AA       |
+--------+----------------+----------------+
|   AS   |     Square     |    Rhombus     |
|--------+----------------+----------------+
|  ~AS   |    Rectangle   |  Parallelogram |
+--------+----------------+----------------+

If not OA, then:

Determine if there are exactly 2 pairs of equal adjacent sides and if they are separated (aabb instead of aaab). If so, the shape is a kite.

Determine if there are exactly 1 pair of parallel opposite sides. If so, the shape is a trapezium.

Otherwise, the shape is a quadrilateral.

Code
⍙←{⍵⍺⍺1⌽⍵} defines a new operator. In APL, an operator means a higher-order function. This operator takes 1 functional argument (⍺⍺) and returns a monadic function that:

Rotates (1⌽) the argument (⍵)
Apply ⍺⍺ between it and ⍵

This is especially useful for scalar functions since most of them implicitly map across array arguments, allowing ⍙ to apply those between each adjacent pair of elements with wrap around. For example +⍙1 2 3 4 is 1 2 3 4 + 2 3 4 1 which evaluates to 3 5 7 5.

x←-⍙⎕+.×1 0J1 converts the input coordinate matrix into an array of complex numbers representing the vectors of the 4 sides of the shape.

⎕, when referenced, takes and returns input

1 0J1 represents the vector [1,i] ("vector" in the mathematical sense, and "i" as the square root of -1). In APL, a complex number a+bi is written aJb

+.× matrix multiplication. Mathematically, the result would be a 4×1 matrix. However, +.× is called "inner product" in APL which generalizes matrix multiplication and vector inner product and allows you to do even stuff like "multiply" a 3-dimensional array with a 2-dimensional one. In this case, we are multiplying a 4×2 matrix and a 2-element vector, resulting in a 4-element vector (of the complex number representations of the 4 given vertices).

-⍙ is pairwise subtraction with wrap around as noted above. This gives the vectors of the 4 sides of the shape (as complex numbers). These vectors point in the "reverse" direction but that doesn't matter.

x← stores that into the variable x

2|1+-⍙(12○x)÷○1 finds (a representation of) the exterior angles at the 4 vertices of the shape.

12○x finds the principal argument, in radians, of each of the 4 side vectors.

÷○1 divides by π so that the angles are easier to work with. Thus, all angles are expressed as a multiple of a straight angle.

-⍙ Pairwise subtraction with wrap around as noted above. This gives the 4 exterior angles.

2|1+ The principal argument is capped (-1,1] and pairwise subtraction makes the range (-2,2]. This is bad since the same angle has 2 different representations. By doing "add 1 mod 2", the angle is re-capped at (0,2]. Although all angles are 1 more than what it should be, it's fine if we keep that in mind.

|x finds the magnitude of each of the 4 side vectors

{⍵≡2⌽⍵:≡⍙¨0⍺⍵⋄2 4=+/1=2|+⍙↑⍵(=⍙⍺)} defines and applies a function with the array of 4 exterior angles as right argument ⍵ and the array of 4 side lengths as right argument ⍺.

The function has a guarded expression. In this case, ⍵≡2⌽⍵ is the guard.
If the guard evaluates to 1 then the next expression ≡⍙¨0⍺⍵ is executed and its value returned.
If the guard evaluates to 0, that expression is skipped and the one after that 2 4=...=⍙⍺) gets executed instead.

⍵≡2⌽⍵ checks if both pairs of opposite angles are equal.

2⌽⍵ rotates the angles array by 2 places.
⍵≡ checks if that is the same as ⍵ itself

≡⍙¨0⍺⍵ returns a unique value for each parallelogram-type shape.

0⍺⍵ is the 3-element array of the scalar 0, the side lengths array ⍺, and the angles array ⍵.
≡⍙¨ executes ≡⍙ for each of those elements.
≡⍙ checks if all values of an array are equal by checking if rotating it by 1 gives the same array. Scalars do not rotate so ≡⍙0 returns 1. As noted above, ≡⍙⍺ checks for a rhombus and ≡⍙⍵ checks for a rectangle.

2 4=+/1=2|+⍙↑⍵(=⍙⍺) returns a unique value for each non-parallelogram-type shape. This is achieved by intertwining the checks for kite and trapezium.

2=+/1=2|+⍙⍵ checks for a trapezium.

+⍙⍵ gives the adjacent angle sums. The interior angles of parallel lines sum to a straight angle, thus so does the exterior angles of parallel sides of a quadrilateral. So, each pair of parallel sides should lead to two 1 or -1 in the adjacent angle sums.

1=2| However, the angles in ⍵ are 1 more than what they should be, so the angles actually sum to 1 or 3. This can be checked by "mod 2 equals 1".

+/ sums the array. This gives a count of adjacent angle sums which is 1 or 3.

2= check if that equals 2. (I.e. if there is exactly one pair of parallel sides)

4=+/1=2|+⍙(=⍙⍺) checks for a kite.

(=⍙⍺) gives an array indicating which adjacent sides are equal. Unlike ≡, = work element-wise. Thus, this is a 4-element array with 1s where the length of that side is equal to that of the "next" side.

+⍙ Pairwise sum with wrap around.

1=2| Since (=⍙⍺) gives a boolean array (one with only 0s and 1s), the only possible values of pairwise sum are 0, 1 and 2. So 1=2| is same as just 1=.

+/ sums the array. This gives a count of pairwise sums which is 1.

4= check if that equals 4. The only way that happens is if (=⍙⍺) is 1 0 1 0 or 0 1 0 1. As noted above, this means the shape is a kite.

2 4=+/1=2|+⍙↑⍵(=⍙⍺) intertwines the above checks.

⍵(=⍙⍺) is the 2-element nested array of the array ⍵ and the array (=⍙⍺)

↑ promotes the nested array to a proper matrix. Since ⍵(=⍙⍺) is a 2-element array of 4-element arrays, the result is a 2×4 matrix.

+⍙ Since ⌽ (and, by extension, ⍙) rotates the last (horizontal) axis, +⍙ to a matrix is same as applying +⍙ to each row individually.

1=2| both residue/mod (|) and equals (=) works on a per-element basis, even to matrices.

+/ By default, reduce (/) works along the last (horizontal) axis. So +/ sums along rows and turn a 2×4 matrix into a 2-element simple array.

2 4= Since = works per-element, this checks the kite and trapezium conditions simultaneously.


Remove unnecessary parentheses You are given a string composed with the characters 0123456789+*(). You can assume that string is always a valid mathematical expression.

Your task is to remove the unnecessary parentheses, assuming multiplication has higher priority than addition.

The parentheses should be removed only when they are not needed structurally:

because of multiplication higher priority: 3+(4*5) => 3+4*5
because of multiplication or addition associativity: 3*(4*5) => 3*4*5
when they are redundant around an expression: 3*((4+5)) => 3*(4+5)

Parentheses should be kept when they could be simplified because of specific number values:

1*(2+3) should not be simplified to 1*2+3
0*(1+0) should not be simplified to 0*1+0

Examples:

(4*12)+11         ==>    4*12+11
(1+2)*3           ==>    (1+2)*3
3*(4*5)           ==>    3*4*5
((((523))))       ==>    523
(1+1)             ==>    1+1
1*(2*(3+4)*5)*6   ==>    1*2*(3+4)*5*6
1*(2+3)           ==>    1*(2+3)
0*(1+0)           ==>    0*(1+0)

(((2+92+82)*46*70*(24*62)+(94+25))+6)    ==>    (2+92+82)*46*70*24*62+94+25+6

Mathematica, 105 97 91 bytes

-6 bytes thanks to Roman!

a=StringReplace;ToString@ToExpression@a[#,{"*"->"**","+"->"~~"}]~a~{" ** "->"*","~~"->"+"}&

Replaces + and * with ~~ (StringExpression) and ** (NonCommutativeMultiply) respectively, evaluates it, stringifies it, and replaces the operators back.


π Day puzzle for 3/14 Happy π Day. The goal of this question is to calculate the area for a circle of radius 3, where A = πr².

The catch is that you have to use the constant π that is defined in a different language than the one you are programming in. For example, you can write a C program that uses Fortran's MATH::PI, or a Python program that uses Java's java.lang.Math.PI.

Rules:

Your code must use a stored value of π from a different language for the calculation. (i.e. it must be stored in a constant or math library.)
All of the code for your program must fit in a single file. For example, You cannot write one program in C to print π, then another in Java to run the C program. (However, you can write a Java program that writes and compiles a C program by itself.)
You cannot download π from a webpage and claim that your constant came from PHP/ASP/HTML.

Here is an example that runs in Bash, and uses Python's stored math.pi value:

#!/bin/bash
PI=`python -c 'import math; print math.pi'`
bc -l <<< "3 * 3 * $PI"

Output:

28.27433388231

This is a Popularity Contest, so the entry with the most votes after a week wins.

Edit: After one week, the prize goes to DigitalTrauma with 93 points. Thanks for the awesome assembler tip - I did not know that the the FPU stored the constant in hardware. I expected this contest to be about finding funny ways to throw clock cycles away, but that one could actually save a few.

* Image courtesy of: http://xkcd.com/10/

C + x86 assembly
Not satisfied with a constant defined in the software of your language?  Why not use a language that can access a constant value of PI right from your FPU hardware:
#include <stdio.h>

int main (int argc, char **argv) {
    double pi;
    __asm__("fldpi" : "=t" (pi));
    printf("%g\n", 3 * 3 * pi);
    return (0);
}


The Koszul Sign Rule A Bit of Background

The exterior algebra is a central object in topology and physics (for the physics concept cf. fermion). The basic rule dictating the behavior of the exterior algebra is that \$yx = -xy\$ (and consequently \$x^2 = -x^2 = 0\$). Applying this rule twice we see that \$yzx = -yxz = xyz\$.

The product of two monomials is 0 if any repeated variable occurs, e.g. \$vxyz * stuv = 0\$ because \$v\$ is repeated. Otherwise, we want to put the variables into some standard order, say alphabetical order, and there is a sign introduced that counts how many variables we passed by each other, so for example \$tvy * suxz = +stuvxyz\$ because it takes a total of six crossings to put \$tvysuxz\$ into alphabetical order (on each line I have highlighted the most recently swapped pair):
$$tvy * suxz = +\, tvy\;suxz\\
\phantom{tvy * suxz } {}= -tv\mathbf{\large sy}uxz\\
\phantom{tvy * suxz } {}= +t\mathbf{\large sv}yuxz\\
\phantom{tvy * suxz } {}= -\mathbf{\large st}vyuxz\\
\phantom{tvy * suxz } {}= +stv\mathbf{\large uy}xz\\
\phantom{tvy * suxz } {}= -st\mathbf{\large uv}yxz\\
\phantom{tvy * suxz } {}= +stuv\mathbf{\large xy}z\\
$$
Your task will be to compute this sign.

This is a special case of the Koszul Sign Rule which determines the sign of the terms in many sums in math.
If you are familiar with determinants, the sign in the determinant formula is an example.

Task

You will take as input two 32 bit integers \$a\$ and \$b\$, which we will interpret as bitflags. You may assume that \$a\$ and \$b\$ have no common bits set, in other words that \$a\mathrel{\&}b = 0\$. Say a pair of integers \$(i, j)\$ where \$0\leq i,j < 32\$ is an "out of order pair in \$(a,b)\$" when:

\$i < j\$,
bit \$i\$ is set in \$b\$, and
bit \$j\$ is set in \$a\$.

Your goal is to determine whether the number of out of order pairs in \$(a,b)\$ is even or odd. You should output true if the number of out of order pairs is odd, false if it is even.

Input

A pair of 32 bit integers. If you would like your input instead to be a list of 0's and 1's or the list of bits set in each integer, that's fine.

Output

true or any truthy value if the number of out of order pairs is odd, false or any falsey value if it is even.
Alternatively, it is fine to output any pair of distinct values for the two cases.
It is also fine to output any falsey value when the number of out of order pairs is odd and any truthy value when the number of out of order pairs is even.

Metric

This is code golf so shortest code in bytes wins.

Test cases

    a = 0b000000
    b = 0b101101
    output = false // If one number is 0, the output is always false.

    a = 0b11
    b = 0b10
    output = UNDEFINED // a & b != 0 so the behavior is unspecified.

    a = 0b01
    b = 0b10
    output = true // 1 out of order pair (1,2). 1 is odd.

    a = 0b011
    b = 0b100
    output = false // 2 out of order pairs (1,2) and (1,3). 2 is even.

    a = 0b0101
    b = 0b1010
    output = true // 3 out of order pairs (1,2), (1,4), (3,4). 3 is odd.

    a = 0b0101010 // The example from the introduction
    b = 0b1010101
    output = false // 6 out of order pairs (1,2), (1,4), (1,6), (3,4), (3,6), (5,6).

    a = 33957418
    b = 135299136
    output = false

    a = 2149811776
    b = 1293180930
    output = false

    a = 101843025
    b = 2147562240
    output = false

    a = 1174713364
    b = 2154431232
    output = true

    a = 2289372170
    b = 637559376
    output = false

    a = 2927666276
    b = 17825795
    output = true

    a = 1962983666
    b = 2147814409
    output = true

// Some asymmetric cases:
    a = 2214669314
    b = 1804730945
    output = true

    a = 1804730945
    b = 2214669314
    output = false

    a = 285343744
    b = 68786674
    output = false

    a = 68786674
    b = 285343744
    output = true

    a = 847773792
    b = 139415
    output = false

COW, 363 285 bytes
moOoommoOmoOmoOoomMOOmoOmOoMOOMOomOoMoOmoOMMMMOOMMMMOomOoMOomoOmoOMoOmOoMMMOOOmooMMMmoomoOMMMOOOmOoMMMmOoMOOmOoMMMmoOmoOmoOMMMMOOMOomoOMMMMOOMMMMOoMOoMMMOOOmooMMMMoOmOomoomOomOoOOOmoomOomOoMOOMOomoOMoOmOoMMMMOOMMMMOomoOMOomOomOoMoOmoOMMMOOOmooMMMmoomOoMMMOOOmoOMMMmoOmoOmoOmoomoOmoOOOM

Try it online!
A major change! (It's faster but still test cases exceed the 60 seconds timeout on TIO)
Now I like it better, it's cleaner, symmetric and I've brute forced the memory cells disposition for least number of movements.
The idea is to directly operate in terms of parity. Information in both LSB will be used in each iteration and then a and b will be halved, until b=0.

Every a%2 is calculated (during repeated subtraction) alternating +1 and -1 in one memory cell, so that their partial sum p is available.
When a '1' is found in b, the parity (the answer) is toggled p many times.

Detailed Explanation:
moo ]    mOo <    MOo -    OOO *    OOM i
MOO [    moO >    MoO +    MMM =    oom o

[0]: a/2     [1]: a     [2]: Sum(a%2)     [3]: b%2     [4]: b     [5]: b/2     [6]: parity

>i>>>i                        ;  Read a in [1] and b in [5]
[                             ;  Loop while [5] is non-zero
    ><                        ;     Just 2 instructions for free cause COW doesn't handle consecutive parethesis :D
    [                         ;     Loop while [5] is non-zero
        -<+>=[=-<->>+<=*]=    ;         SECTION B
    ]                         ;     [5] is 0, [3] is b%2, [5] is b/2
    >=*<=                     ;     Copy [5] in [4], delete [5]
    <                         ;     Point to [3]
    [                         ;     Loop if [3] is non-zero. '1' it's been found in b, parity gets updated
        <=>>>=                ;         Copy [2] in [5]
        [                     ;         Loop while [5] is non zero
            -                 ;             Decrement [5]
            >=[=--=*]=+<      ;             TOGGLE [6]
        ]                     ;
        <<*                   ;         Delete [3] (to exit the loop)
    ]                         ;
    <<                        ;     Point to [1]
    [                         ;     Loop while [1] is non-zero
        ->+<=[=->-<<+>=*]=    ;         SECTION A
    ]                         ;     [1] is 0, a%2 is added in [2], [0] is a/2
    <=*>=                     ;     Copy [0] in [1], delete [0]
    >>>                       ;     Point to [5]
]                             ;     a's and b's LSB have been treated. Now a=a/2 and b=b/2
>>o                           ;  Print [6]

SECTION A ≈ SECTION B is repeated subtraction that divide \$n\$ (a or b, resp.) by \$2\$.
This can't be done in one single step (i.e. --), because \$0\$ can't be surpassed in order to stop (so it'd be -[- =*]=). These sections contextually produce \$n\bmod 2\$ (LSB).
TOGGLE is a toggling method:
When target is 0 it fails the condition and simply +1 is done.
When target is 1 it passes the condition and it's set to -1 so that +1 on exit makes it 0.
Copy, delete, and paste in the same memory cell is a tecnique to treat a while loop like an if loop, also the seemgly useless copy-paste at the beginning of these (=[=) serves to balance the ending one (=*]=) in case if condition fails.


R.E.P.A.I.R. T.H.E. K.E.Y.B.O.A.R.D Sequel of this AWESOME challenge
You, a genius tech prodigy detective, have successfully disarmed the bomb and want to break into the computer. The police found the password 67890-=yuiop[]hjkl;'\vbnm^&*()_+:"| on a piece of paper, but much of the keyboard is broken and there are no other ways of inputting characters.
The only characters left to use are 12345QWERTASDFG<>ZXCqwertasdfgzxc!@#$% and also Tab, Space, and Newline. However, a fairy appears and gives you one more character of your choice.
Using only these 42 characters, produce as many of the password's 35 characters as you can. Write a separate program/function for each password character.
Scoring:

Primary scoring is how many characters you can produce (1–35).

Secondary, tie-breaking score is the total length of your programs/functions.

Standard loopholes apply
Thanks to @Adám for rework

Deadfish, all 35 characters, 444 bytes
Uses s, d, and c, which are allowed, plus i as an extra.
6 iisiiisiiiiic
7 iisiiisiiiiiic
8 iisiiisiiiiiiic
9 iiisdsdddddddc
0 iisiiisdc
- iisiiisddddc
= iiisdsdddc
y iiisiisc
u iiisiisddddc
i iiisisiiiiic
o iiisisiiiiiiiiiiic
p iiisiisdddddddddc
[ iiissiiiiiiiiiic
] iiisisdddddddc
h iiisisiiiic
j iiisisiiiiiic
k iiisisiiiiiiic
l iiisisiiiiiiiic
; iiisdsdddddc
' iisiisiiic
\ iiisisddddddddc
v iiisiisdddc
b iiisisddc
n iiisisiiiiiiiiiic
m iiisisiiiiiiiiic
^ iiisisddddddc
& iisiisiic
* iisiisiiiiiic
( iisiisiiiic
) iisiisiiiiic
_ iiisisdddddc
+ iisiisiiiiiiic
: iiisdsddddddc
" iisiisddc
| iiisiisiiic

Unless I did my coding wrong, I believe these are necessarily optimal.
Here is the meta-golfer
Explanation
I do a pretty simple BFS by creating a priority queue that orders by length first (so the golfiest solution is always found) and state second (so that it doesn't waste time on ridiculously large numbers caused by repeated application of s). Also, I track a visited set to prevent revisiting values with suboptimal-length code.
Then, each time, I just add the state transitions (L,x,c)->(L+1,x+1,c+"i"), (L,x,c)->(L+1,x-1,c+"d"), and (L,x,c)->(L+1,x*x,c+"s") where L is the code length, x is the current number, and c is the current code.
My meta-golfer code is fully commented if you want a more detailed explanation.


Left Center Right (LCR) code golf At a party, I was introduced to the game LCR. Now it's not a great game as there's no skill but only random chance. But it got me thinking, I could code this, and I made a quick program in R to model the game.

Rules of the game modified from Wikipedia to match how we played:

  Each player receives at least 3 chips. Players take it in turn to roll
  three six-sided dice, each of which is marked with "L", "C", "R" on
  one side, and a single dot on the three remaining sides. For each "L"
  or "R" thrown, the player must pass one chip to the player to their
  left or right, respectively. A "C" indicates a chip to the center
  (pot). A dot has no effect.

  If a player has fewer than three chips left, they are still in the
  game but their number of chips is the number of dice they roll on
  their turn, rather than rolling all three. When a player has zero
  chips, they pass the dice on their turn, but may receive chips from
  others and take their next turn accordingly. The winner is the last
  player to put chips into the center.

Contest: write a program in your language of choice that takes input for the number of players and the number of starting chips and simulates a game of LCR, showing the state of the game after each player has rolled.

For example, a game might be output as:

[[[3,3,3,3],0],[[1,4,3,4],0],[[1,4,3,4],0],[[1,4,1,4],2],[[1,4,1,2],4],
[[0,4,1,3],4],[[0,3,2,3],4],[[0,3,0,3],6],[[0,3,1,1],7],[[0,3,1,1],7],
[[2,0,1,1],8],[[2,0,0,1],9],[[2,0,0,0],10],[[0,1,0,0],11],
[[1,0,0,0],11],[[1,0,0,0],11],[[1,0,0,0],11],[[0,0,0,0],12]]

ht: JonathanAllan

The output doesn't have to look exactly like this, but it should be easy to discern the dice roll, how many chips each player has, and how many chips the centre has for each turn.

It's code golf so the shortest code wins.


Recover a bzip2 file The popular .bz2 compression format is used to store all sorts of things. One of the more interesting features is that it consists of several independently decompressible blocks, allowing recovery of partial segments if the file is damaged. The bzip2recover program, included with bzip2, allows recovery of blocks from a bzip2 archive. In this challenge, you will implement a simple clone of bzip2recover.

The basic idea is to scan a bitstream for a particular magic number, and output blocks delimited by this magic number to separate files. Read on for gory details.

Technically, bzip2 files are a bitstream, with every group of 8 bits being stuffed into a byte. The first bit is placed in the most significant bit of a byte, with the eighth bit going in the least significant bit of a byte. Files begin with the header "BZh", and a digit "N" from 1 to 9 indicating the compression level (9 is the most common). Then the bitstream begins.

The bitstream is split up into blocks. Each block encodes N*100KB of uncompressed text (e.g. 900KB of text for compression level 9).
Blocks can begin basically anywhere in the bitstream, and do not necessarily begin on 8-bit boundaries. Blocks begin with a magic number, which is set to the 48-bit sequence 0x314159265359 (in ASCII, "1AY&SY"). For example, the sequence of bytes "73 14 15 92 65 35 90" contains the magic number, offset by 4 bits within the byte.

Your goal will be to take a bzip2 file on stdin, and output each detected BZip2 block to a separate decompressible file. Specifically, your program does the following:

Read and skip the bzip2 header ("BZh" + N)
Scan the bitstream for the magic sequence
Copy the bitstream between two consecutive magic sequences to a new file, with a new BZip2 header and block header. Note that this may require realigning the bitstream to start at a byte boundary, and padding the last byte.

You don't have to care about parsing the blocks, and you can assume that a magic sequence always starts a block (i.e. that it isn't in the middle of a block).

How you name the output files is up to you. The only requirement is that they be clearly sequential somehow (so, e.g. "a b c ... z aa ab" or "1 2 3 4 5 .. 9 10 11 12" are both acceptable).

For a test case, you may use this file from the IPSC 2014 problem-solving contest. The file is a bzip2 file with four blocks. The file as a whole actually decompresses to another bzip2 file with 162 complete blocks. Therefore, you may use these block counts to validate that your solution is getting all of the blocks. (Note that the file actually decompresses even further into more bzip2 files, but you probably don't want to decompress it all the way).

This is code golf, with a twist: your score is the number of bytes in the bz2-compressed version of your source code. (I'm aware this may make submissions larger, but these are the rules!). Since bzip2 compressors may differ in performance, provide a base64-encoded version of the compressed file to prove it's size. (You may therefore be able to obtain a better score by optimizing your program for bzip2, though I don't necessarily expect anyone to do this). Standard loopholes apply.

Python 3 -- 375(534 chars)

It can process the example file d2.in in about 10 seconds, using Pypy3. With CPython 3, it will cost 60 seconds.

It's interesting and weird that some old golf tricks would make the score worse! For example, replacing <space>+<space> by + would increase the score from 375 to 384; replacing all range by R will also increase the score to 384.

Golfed

import sys
from collections import deque
def T(B):
 for i in range(0,len(B),8):
  x=0
  for j in range(min(8,len(B)-i)): x |= B[i + j] << (7-j)
  yield x
V=sys.argv
C=F=0
B=bytearray()
I=open(V[1],'rb')
H=I.read(4)
P=deque([(x>>(7-j)) & 1 for x in b'1AY&SY' for j in range(8)])
Q=deque([0]*48)
for x in I.read():
 for j in range(8):
  b=(x>>(7-j)) & 1
  B.append(b)
  Q.popleft()
  Q.append(b)
  if Q!=P: continue
  C+=1
  M,B=B[:-48],B[-48:]
  if F:F.write(bytes(T(M)))
  F=open(V[2] + str(C),'wb')
  F.write(H)
F.write(bytes(T(B)))

Base64

QlpoOTFBWSZTWSoMWQ0AAMLfgAAQYf901zlibSo/t//kMAFaCIaCQANTTTKMnlGg8oeRpPaoNDDAAAAAaAAAAABKaSGmmpplD0jQaAABo00ZNqLfKsdHBd3QgkQ2wY3RfYpMMjPpsyit5Ee6+k6E6ObzlFT2vmgbSKPkni7ZgDkcwTRiLFBmNCuEX/HtOC8KJ+Rg51SkMCiAGXZpXbvaK+DzMLvaEhAM8reCB8HFAsNYfRghS9+i5/IpLrDzGZVhsbVOpQzHIIVZ7zCCgDkcElOMvTuvfw2bruKz2WQuvEg99gDa8T3Kw2GdyMNjEVFVVQj4sU1MaOTUcwQROwt86LfUZAOJE6HqnB60CFO38NJmpifx+trcQ8x5alqRiEGoKC2wJpPkCXpT7fbtFDbLCLQaplK23qMTC5gqGwCghjN3zEtwyKhCz3kixqBr7gya6yPG03rMOGY9hlmV3tS0W/SdC2taUpCoNSEaEnUXckU4UJAqDFkN


Decode a Rövarspråket string This question is the inverse of this one by James Williams.

Rövarspråket

Rövarspråket is a word game played by Swedish children, from the books about Kalle Blomkvist by Astrid Lindgren.

The basic rules used during encoding are as follows (from Wikipedia):

Every consonant (spelling matters, not pronunciation) was doubled, and
an o was inserted in-between.
Vowels were left intact.

A few examples of decoding:

"hohelollolo" -> "hello"
"MoMinon sosvovävovarore äror fofulollol momedod ålol" -> "Min svävare är full med ål"

Swedish consonants are the same as the English ones, so the program should work with both Swedish and English entries.

The letter "y" is taken as a consonant in this case - as most of the time it is.

Your Task:

Write a program to convert a Rövarspråket string of Swedish letters, inputted through a function or through stdin, into its decoded equivalent.  Shortest answer in bytes wins!

Retina, 19 + 2 = 21 bytes

Retina strikes again! The code for this program consists of two files:

i`([b-z-[eiou]])o.

$1

This reads the input on STDIN and prints the output to STDOUT.

If you call the files pattern.rgx and replacement.rpl, you can run the program simply like

echo "hohelollolo" | ./Retina pattern.rgx replacement.rpl

Explanation

As for the previous answer, if Retina is invoked with 2 files it is automatically assumed to operate in "Replace mode", where the first file is the regex and the second file is the pattern.

Retina can be configured (which includes RegexOptions and other options) by prepending the regex with ` and a configuration string. In this case I'm only giving it i which is the normal regex modifier for case insensitivity.

The pattern itself is a bit more interesting this time. It still uses .NET's character class subtraction to match any consonant in the ASCII range, but then it also matches the following o as well as the character after it (i.e. the copy of the consonant). The replacement then just writes the captured consonant back.

You might be wondering why this is not ambiguous in a case like lololol -> lol. The trick is that matches cannot overlap and are always found from left-to-right. So whenever I encounter a consonant, I include the next two character in the match and replace all of them - the search continues after this. It's quite easy to convince yourself that this kind of greedy algorithm will always decode the input correctly. In fact the pattern could even have been

i`([b-z-[eiou]])..


Operations with Lists Inspired by this question.
Given a list containing numbers, print:

The sum and product of the numbers in the list
The average and median
The differences between each term in the list (e.g. [1,2,3] -> [1,1]: 1+1=2, 2+1=3)
The list, sorted ascending
The minimum and maximum of the list
The standard deviation of the list

For reference:
Standard Deviation
$$\sigma=\sqrt{\frac1N\sum^N_{i=1}(x_i-\mu)^2}$$
Where \$\mu\$ is the mean average, \$x_i\$ is the \$i\$th term in the list, and \$N\$ is the length of the list.
Shortest code wins. Good luck!


Code Golf Simulated Golf Given a list of hole yardages, green sizes, a slice angle and a max distance, compute a golf score.

Assumptions

Earth is flat
All greens are circular
Slice angle will be between -45 and 45 degrees and will be given in degrees
All distances in the same metric (yards or meters, doesn't matter)
No out of bounds, obstructions or doglegs
Max score on any hole is 8
All shots travel the lesser of max distance or distance to the hole, in a direction defined by the angle to the hole plus the slice angle.
Distance is measured as the straight line or Euclidean distance between the start and end point.
Max distance and slice angle are the same for all shots on all holes
The golfer always two-putts once on the green (or exactly on the edge of the green).

Example

Let's look at the hacker from the test case #5 below for hole #2.  The hacker can hit the ball 320 yards, but always slices 30 degrees.  If we assume without loss of generality that the tee box is at {0,0} and the green is at {497,0}, then he will hit shots to the following points, arriving on the green with the 7th shot:

{{0.,0.},{277.128,-160.},{547.543,-131.372},{569.457,7.67088},{502.872,37.2564},{479.159,7.92741},{490.646,-7.85868},{500.078,-4.22987}}

At this point, his score would be 9 due to the two putts required, so the final score for him gets capped at 8, per the assumptions.

Graphically, it will look like this:

Test Cases

All the test cases have standard 18-hole courses

Case#1
{MaxDistance->280,SliceAngle->10,HoleDistances->{181,368,161,416,158,526,377,427,509,148,405,443,510,494,396,388,483,172},GreenDiameters->{26,18,17,23,27,23,21,23,25,21,19,24,21,23,25,24,22,22}}
Scores:
{4,5,4,5,4,5,5,5,5,4,5,5,5,5,5,5,5,4}
Output: 85

Case#2 (same course as Test Case #1, shorter more accurate golfer)
{MaxDistance->180,SliceAngle->5,HoleDistances->{181,368,161,416,158,526,377,427,509,148,405,443,510,494,396,388,483,172},GreenDiameters->{26,18,17,23,27,23,21,23,25,21,19,24,21,23,25,24,22,22}}
Scores:
{4,5,4,5,4,6,5,5,6,4,5,5,6,6,5,5,5,4}
Output: 89

Case#3 (Same golfer as test case #1, shorter course)
{MaxDistance->280,SliceAngle->10,HoleDistances->{147,497,110,528,409,118,196,154,134,514,374,491,131,138,523,478,481,494},GreenDiameters->{32,16,36,25,32,20,30,30,33,29,25,26,26,25,33,28,21,28}}
Scores:
{4,5,4,5,5,4,4,4,4,5,5,5,4,4,5,5,5,5}
Output: 82

Case#4 (Same course as test case #3)
{MaxDistance->180,SliceAngle->5,HoleDistances->{147,497,110,528,409,118,196,154,134,514,374,491,131,138,523,478,481,494},GreenDiameters->{32,16,36,25,32,20,30,30,33,29,25,26,26,25,33,28,21,28}}
Scores:
{3,6,3,6,5,4,4,3,3,5,5,5,3,3,5,5,6,5}
Output: 79

Case#5 (Hacker)
{MaxDistance->320,SliceAngle->30,HoleDistances->{147,497,110,528,409,118,196,154,134,514,374,491,131,138,523,478,481,494},GreenDiameters->{32,16,36,25,32,20,30,30,33,29,25,26,26,25,33,28,21,28}}
Scores:
{6,8,5,8,7,6,6,6,6,8,8,8,6,6,8,8,8,8}
Output: 126

Rules

Any format can be used for the input. Output is simply the number of simulated strokes, so should be an integer.
This is code-golf so the shortest answer in bytes wins.  Standard loopholes apply.

JavaScript (ES7), 128 126 bytes

(m,a,D,S,t=0)=>S.map((s,i)=>t+=(r=(f=d=>d>s/2?1+f((l=d<m?d:m,l*l+d*d-2*d*l*Math.cos(a*Math.PI/180))**.5,s):2)(D[i]))<8?r:8)&&t

Try it online!

Explanation

Because only the distance from the ball to the hole matters and not the coordinates of the ball, we can write an algorithm that calculates how close the ball gets to the hole with each shot, then run that repeatedly until the ball reaches the green. But how do we do this?

Re-using OP's helpful diagram explaining ball movement, with MS Paint modifications:

We have access to these numbers:

d, the current distance from ball to hole;
θ, the slice angle; and
l, the length of the shot (minimum of d and the max shot length).

And the goal is to find x, the distance from ball to hole after the shot is taken.

First we note that a and b are simply l cos θ and l sin θ, respectively. We can see that by the Pythagorean theorem, x can be represented as sqrt(b2 + (d-a)2). Expanding this out, we get

x = sqrt(b^2 + (d - a)^2)
  = sqrt((l*sin(θ))^2 + (d - l*cos(θ))^2)
  = sqrt((l^2 * sin^2(θ)) + (d^2 - 2*d*l*cos(θ) + l^2 * cos^2(θ))
  = sqrt(l^2 * sin^2(θ) + l^2 * cos^2(θ) + d^2 - 2dl*cos(θ))
  = sqrt(l^2 * (sin^2(θ) + cos^2(θ)) + d^2 - 2dl*cos(θ))
  = sqrt(l^2 * 1 + d^2 - 2dl*cos(θ))
  = sqrt(l^2 + d^2 - 2dl*cos(θ))

And so, the new distance from ball to hole will be sqrt(l2 + d2 - 2dl cos θ). Then we count the iterations it takes to get this distance within the radius of the green, add 2, and cap at 8 to get the final score for that hole.

(Thanks to @LegionMammal978 for pointing out that all of the calculations I made are a direct result of the law of cosines...)

Interestingly enough, when the ball is closer to the hole than its max shot, l = d and we can simplify the formula quite a bit further:

x = sqrt(l^2 + d^2 - 2dl*cos(θ))
  = sqrt(d^2 + d^2 - 2d^2*cos(θ))
  = sqrt(2d^2 - 2d^2*cos(θ))
  = sqrt(d^2(2 - 2cos(θ)))
  = d * sqrt(2 - 2cos(θ))

To find the # of remaining iterations, we could then simply find d / r (where r = the radius of the green) and divide that by sqrt(2 - 2cos(θ)), then take the ceiling of the result and add 2. Unfortunately, this doesn't seem to be as short as just finding the smaller of d and the max shot length.


Composite Number Sequences Inspired by this question
Given a positive integer \$n\$, your code must output the first \$n\$ composite numbers.
Input / Output
You may write a program or a function. Input is through STDIN or function argument and output is to STDOUT, or function return value.
Output can be a List, Array, or String.
Examples
 0 ->
 1 -> 4
 2 -> 4, 6
 3 -> 4, 6, 8
13 -> 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22

Rules

As always standard loopholes are disallowed.

Built-ins that generate prime or composite numbers are not allowed.

Built-ins relating to prime or composite numbers are not allowed.

Pyth - 10 bytes
A valid answer. Uses Wilson's Theorem.
.f%h.!tZZQ

Try it online here.

Old answer
Pyth - 6 chars
Uses builtin for prime factorization, not prime checking.
.ftPZQ

Try it online here.
.f  Q         First n that passes filter of lambda Z, uses input for how many
 t            Tail. This makes all that have len-one prime factorization become empty list, and thus falsey.
  P           Prime factorization - primes have a len-one factorization.
   Z          Lambda var


Output Rhombus Sequence without Nested Loops The following is the rhombus sequence.

1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321

Your task is to output this, taking no input and using standard output methods (STDOUT, list of numbers or list of strings, etc.).

There's a hitch. You may only use up to one loop - no nested loops. Recursion counts as a loop, so you can either recurse or loop, not both. Non-standard languages will be dealt with on a case-by-case basis.

This is code-golf, so shortest program in bytes wins. This is kolmorgorov-complexity, so you may not take any input whatsoever.

Mathematica, 23 bytes
((10^#-1)/9)^2&~Array~9

Try it online!


Rotate every 2x2 block in a matrix The Challenge
Given a n x m matrix with n > 1 and m > 1  filled with integers

1 2 3
4 5 6

and a list of integers with exactly as many values as 2x2 blocks in the matrix ((n-1)*(m-1) if you need the exact number)

[1, 2]

Output the matrix with every 2x2 block rotated by the current value in the list in the given order. The example above would yield

4 6 2
5 3 1

The first block gets rotated one time to the right and the second block gets rotated two to the right.
Notes

A positive integer means you rotate right by that many steps.
A negative integer means you rotate left by that many steps.
A zero means that you don't rotate.
You rotate the blocks row-wise. That means that you start in the first row and go to the right. Once you rotated every block in that row you go to the next one. At the end every block was rotated exactly once.
Keep in mind that the blocks overlap each other. The first matrix above has the blocks [[1,2],[4,5]] and [[2,3],[5,6]] for example.
Each rotation of a block affects the rotation on the adjacent blocks. This is why you have to do the rotations in the pattern described above.

Rules

You may take the input in the most convenient format. Please specify in your answer which one you use. This does not allow you to read the matrix block-wise though.
Function or full program allowed.
Default rules for input/output.
Standard loopholes apply.
This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Test cases
Input format here is a list of lists for the matrix and a normal list for the values.

[[1,2],[3,4]], [-3] -> [[4,1],[3,2]]
[[1,1,1],[1,1,1]], [-333, 666] -> [[1,1,1],[1,1,1]]
[[1,2,3],[4,5,6]], [1,2] -> [[4,6,2],[5,3,1]]
[[1,2,3],[4,5,6],[7,8,9]], [4,0,12,-20] -> [[1,2,3],[4,5,6],[7,8,9]]
[[1,2,3,4,5],[5,4,3,2,1],[1,2,3,4,5]], [2,-3,4,1,6,24,21,-5] -> [[4,1,5,2,4],[2,1,3,5,5],[3,2,4,3,1]]

Happy Coding!

CJam (42 40 bytes)

{(\@2$,(/.{@a@a+z(\@.{4,={+2/zW%~}*}z~}}

Online demo

Basically this applies the same technique twice in order to fold the block

{4,={+2/zW%~}*}

which operates on a 2x2 matrix and a number of times to rotate.

[first row] [[second row] [third row] ... [last row]] [value_0 value_1 ... value_n]

can be processed with

.{block}

and has the effect of

[first row]
[second row] value_0 {block}~
[third row] value_1 {block}~
...

because . (like % in CJam) doesn't gather the results into an array until it's finished.


How does math work in Anastasiya's world? Background:

Standard operation math like basic addition and multiplication in the real world work like these:

12 + 123 = 135

and

12 * 123 = 1476

That's not interesting and boring! Many schools are already interpreting this as practice, practice, practice of formal algorithms. That implies a pretty rigid and boring mathematical diet and is not what is intended in this challenge. Get ready to play some fun on our beloved site.

Consider the process of adding two positive integer numbers, then adding again all the digits of its result. Repeating with the addition until only a single digit is obtained. For example:

The result of 12 + 123 is 135.
Adding all the digits of 135 we obtain 1 + 3 + 5 = 9.

The number of steps required to obtain a single digit value 9 in this repeated addition is 2.

As with the previous process of the addition, the multiplication of two positive integer numbers follows the same process. Multiply all the digits of its result and then repeating this process until only a single digit remains. Take the above example:

The result of 12 * 123 is 1476.
Multiply all the digits of 1476 we obtain 1 * 4 * 7 * 6 = 168.
Multiply again all the digits of 168 we obtain 1 * 6 * 8 = 48.
Multiply again all the digits of 48 we obtain 4 * 8 = 32.
Multiply once again all the digits of 32 we obtain 3 * 2 = 6.

The number of steps required to obtain a single digit value 6 this repeated multiplication is 5.

For this challenge's sake and avoiding any misuse of math notations, I introduce these two dummy notations: (+) and (*), but you may use any notation you like, which work like the followings:

The operation of repeated addition process to obtain a single value is 12 (+) 123 = 9.
The operation of repeated multiplication process to obtain a single value is 12 (*) 123  = 6.

Challenge:

The challenge is to write either a program or a function which can perform both of operations as explained in the background section: (+) and (*).

Input:

The inputs of the program or the function are two positive integers and one operation either (+) and (*). The format of the input is an arbitrary choice of the programmer. You may format the input, for example, a (+) b or F(a, (+), b) or any format you wish.

Output:

The output of the program or the function must contain the result of operation and the number of steps required with freestyle format as you wish.

Test Cases (ignore the input and output format):

    81 (+) 31       -->   (4 ; 2)
    351 (+) 14568   -->   (6 ; 3)
    21 (*) 111      -->   (8 ; 3)
    136 (*) 2356    -->   (0 ; 2)

General rules:

This is code-golf, so the shortest answer in bytes wins the challenge.
Don't let esolangs discourage you from posting an answer with regular languages. Enjoy this challenge by providing an answer as short as possible with your programming language. If you post a clever answer and a clear explanation, your answer will be appreciated (hence the upvotes) regardless of the programming language you use.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/ method with the proper parameters, full programs, etc. The choice is yours.
If possible, your program can properly handle large numbers. If not, that will just be fine.

Let the game begin!!

Dyalog APL, 33 32 30 29 bytes

This extends APL to include the prefix notation +/A n₁ n₂ and ×/A n₁ n₂. (In fact, you can use any operation to the left of the /A.) Returns a list of {result, repetition count}.

A←{(⊃,≢)⍺⍺{∪⍵,⍨⍺⍺⍎¨⍕⊃⍵}⍣≡⍺⍺⍵}

  A←{ define a higher-order function in terms of left-hand function ⍺⍺, and right-hand argument ⍵

    (⊃,≢) the first element of, followed by the count of

    ⍺⍺{ the supplied function (+/ for sum or ×/ for product) fed to the higher-order function

      ∪ the unique elements of

      ⍵,⍨ the argument appended to

      ⍺⍺ the fed function applied to

      ⍎¨ the evaluation of each character of

      ⍕ the character representation of

      ⊃⍵ the first element of the argument

    }⍣≡ applied repeatedly until the result is identical to the argument, beginning with

    ⍺⍺⍵ the originally fed function (+/ or ×/) applied to the original argument

  } [end of higher-order function definition]

TryAPL online! (⍎ has been emulated with e for security reasons.)

Thanks to @ngn for saving a byte.

0 bytes (in jest)

Dyalog APL actually already has full support for Anastasiyan math; instead of (+) and (×), it uses +{n←0⋄n,⍺⍺{n+←1⋄⍺⍺/⍎¨⍕⍵}⍣=⍵⍺⍺⍨⍺} and ×{n←0⋄n,⍺⍺{n+←1⋄⍺⍺/⍎¨⍕⍵}⍣=⍵⍺⍺⍨⍺}.

Try 81 +{(⊃,≢)⍺⍺{∪⍵,⍨⍺⍺e¨⍕⊃⍵}⍣≡⍺⍺/⍺⍵} 31 and 21 ×{n←0⋄n,⍺⍺{n+←1⋄⍺⍺/e¨⍕⍵}⍣=⍵⍺⍺⍨⍺} 111.


Build an RSA encoder Your task is to build a function in any language that takes a message m, an encryption e, and a modulus k (all positive integers), and takes m to the power of e modulo k. Your solution must not be a theoretical one, but one that would work on a reasonable computer such as your own, for RSA keys of currently used sizes such as 2048 bits.

Shortest code wins.

Python – 5

Python 3 built-in function pow have third parameter. So Python 3 already have built-in RSA encoder

r=pow


Solve a Diagonal Burrows-Wheeler transform Introduction
In this challenge you will be solving diagonal Burrows-Wheeler transforms. Here is a general overview of what a diagonal Burrows-Wheeler transform is. To encode a message, you first must guarantee that it is odd in length (i.e. 5, 7, 9, etc.). Then you make a grid, n by n, where n is the length of the message. The first row is the original message. Each row after that is the row above it, but shifted 1 character left with the first character moving to the back. For example:
Hello World
ello WorldH
llo WorldHe
lo WorldHel
o WorldHell
 WorldHello
WorldHello
orldHello W
rldHello Wo
ldHello Wor
dHello Worl

Then you take each letter on the NW to SE diagonal and put that into a new string:
Hello World  H
ello WorldH  l
llo WorldHe  o
lo WorldHel  W
o WorldHell  r
 WorldHello  d
WorldHello   e
orldHello W  l
rldHello Wo  (space)
ldHello Wor  o
dHello Worl  l

Your encoded message is HloWrdel ol. To decode, first take the length of the encoded message, add 1, and divide by 2. Lets call this number x. Now that we know x, starting at the first letter, each letter is x after the last, looping around. For example:
H   l   o   W   r   d   e   l     o   l
1

Then...

H   l   o   W   r   d   e   l     o   l
1                       2

And again...

H   l   o   W   r   d   e   l     o   l
1   3                   2

Until you get...

H   l   o   W   r   d   e   l       o   l
1   3   5   7   9  11   2   4   6   8  10

Now just rearrange the letters in the correct order to get Hello World!
Challenge
Your challenge is to write either two programs, functions, or one of each. However, both must use the same language. The first program will accept a string as input via STDIN, program arguments, or function parameters and encode it using this method. The second program will accept a string as input via STDIN, program arguments, or function parameters and decode it using this method.
Requirements
First Program/Function

A single string input using any method listed above.
Must encode the string using a diagonal Burrows-Wheeler transform style.

Second Program/Function

A single string input using any method listed above.
Must decode the string using a diagonal Burrows-Wheeler transform style.

Constraints

You cannot use any built-in or external functions that accomplish this task.
Standard loopholes are not allowed.
Both programs/functions must be in the same language.

Scoring
This is code golf, so shortest program in bytes wins.
If I need to add more information, leave a comment!

CJam, (4 + 8 = ) 12 bytes

Encoding program:

q2/z

Try it online here

Decoding program:

q_,2/)/z

Try it online here

How (or rather, why) they work:

The Diagonal Burrows-Wheeler transform is basically every other character of the string, with wrapping from the end. If we treat the String as a 2D matrix of 2 columns, it simply boils down to taking the transform of the matrix. Example:

Hello World

Is represented as 2D matrix as

He
ll
o
Wo
rl
d

Now, simply reading it column wise, give:

HloWrdel ol

Which is the Burrows-Wheeler transform.

Decoding is simply reverse of the process, write the string as a 2 row 2D matrix and read column wise.

Code expansion:

Encoder:

q          "Read the input";
 2/        "divide it into sub arrays of 2 characters";
   z       "Take transform";

Decoder:

q_,        "Read the input, take copy and get length of copy";
   2/      "Divide the length by 2";
     )/    "Increment and split the input into two rows";
       z   "Take transform";


Hello world!!! Fibonacci distribution Your program should output exactly: Hello world!!! with or without linefeed after.
Your program should take no input.
Sourcecode character distribution must be correct according to:

The number of numeric characters (0-9) must be exactly one fibonacci sequence number.
The number of other non-numeric characters !(0-9) in the sourcecode must be exactly the fibonacci sequence number before the above fibonacci sequence number.

Four examples of valid character distribution in sourcecode:

13 numeric, 8 non-numeric characters.
34 numeric, 21 non-numeric characters.
55 numeric, 34 non-numeric characters.
89 numeric, 55 non-numeric characters.

This is code-golf, shortest code in bytes wins! Good luck!

Edit: As this question has constraints on the sourcecode size in combination with being code-golf the accepted answer (if more than one share the equal winning character length) will be the answer with most votes (and least character-count): 2014-03-01.

Windows Command Prompt - 34, 8, 5 chars, (2 below)

*These ones may or may not be breaking rule 2, but here it is anyway

%~099

Name the file:

&start call echo Hello world!!!&exit -b .cmd

Now lets corrupt the file-system a little - 2 chars (or less if you want)

A1

Name the file (using your preferred unorthodox method):

"&start call echo Hello world!!!&exit&.cmd

How does this work:

Since cmd scripts are invoked with 'cmd.exe /C "%1" %*' the executed command will be:

cmd.exe /C "c:\PATH_TO_THE_SCRIPT\"&start call echo Hello world!!!&exit&.cmd"

which will in the following order:

Fail to execute "c:\PATH_TO_THE_SCRIPT\"
Open a new shell printing Hello world!\n
Exit the original shell


Length of a UTF-8 byte sequence Determine the length of a UTF-8 byte sequence given its first byte. The following table shows which ranges map to each possible length:

  Range    Length
---------  ------
0x00-0x7F    1
0xC2-0xDF    2
0xE0-0xEF    3
0xF0-0xF4    4

Notes on gaps in the table: 0x80-0xBF are continuation bytes, 0xC0-0xC1 would start an overlong, invalid sequence, 0xF5-0xFF would result in a codepoint beyond the Unicode maximum.

Write a program or function that takes the first byte of a UTF-8 byte sequence as input and outputs or returns the length of the sequence. I/O is flexible. For example, the input can be a number, an 8-bit character or a one-character string. You can assume that the first byte is part of a valid sequence and falls into one of the ranges above.

This is code golf. The shortest answer in bytes wins.

Test cases

0x00 => 1
0x41 => 1
0x7F => 1
0xC2 => 2
0xDF => 2
0xE0 => 3
0xEF => 3
0xF0 => 4
0xF4 => 4

Z80Golf, 19 14 bytes

00000000: 2f6f 3e10 37ed 6a3d 30fb ee07 c03c       /o>.7.j=0....<

Try it online!

-5 bytes thanks to @Bubbler

Example with input 0x41-Try it online!
Assembly

Example with input 0xC2-Try it online!

Example with input 0xE0-Try it online!

Example with input 0xF4-Try it online!

Assembly:

;input: register a
;output: register a
byte_count:			;calculate 7^(log2(255^a))||1
	cpl			;xor 255
	ld l,a
	log2:
		ld	a,16
		scf
	log2loop:
		adc	hl,hl
		dec	a
		jr	nc,log2loop
	xor 7
	ret nz
	inc a

Try it online!


2-Dimensional Bubble Sort Sorting makes no sense for a 2-dimensional array... or does it?

Your task is to take an input grid and apply a bubble-sort-like algorithm to it until all values in the grid are non-decreasing from left to right and top to bottom along every row and column.

The algorithm works as follows:

Each pass goes row by row, top to bottom, comparing/swapping each cell with its right and below neighbors.

if the cell is greater than only one of its right and below neighbors, swap with the one that it is greater than
if the cell is greater than both its right and below neighbors, swap with the smaller neighbor
if the cell is greater than both its right and below neighbors, which are the same value, then swap with the below neighbor.
if the cell is not greater than either of its right and below neighbors, do nothing

Continue this until no swaps are made throughout the entire pass. This will be when every row and column are in order, left to right and top to bottom.

Example

4 2 1
3 3 5
7 2 1

The first row of the pass will swap the 4 and the 2, then the 4 with the 1.

2 1 4
3 3 5
7 2 1

When we get the the middle 3, it will be swapped with the 2 below

2 1 4
3 2 5
7 3 1

Then the 5 gets swapped with the 1 below

2 1 4
3 2 1
7 3 5

The last row of the first pass moves the 7 all the way to the right

2 1 4
3 2 1
3 5 7

Then we go back to the top row again

1 2 1
3 2 4
3 5 7

And continue row by row...

1 2 1
2 3 4
3 5 7

... until the grid is "sorted"

1 1 2
2 3 4
3 5 7

Another Example

3 1 1
1 1 1
1 8 9

becomes

1 1 1
1 1 1
3 8 9

rather than

1 1 1
1 1 3
1 8 9

because the downward swap takes priority when both the right and below neighbors of a cell are equal.

A step-by-step reference implementation can be found here.

Test cases

5 3 2 6 7 3 1 0
3 2 1 9 9 8 3 0
3 2 2 8 9 8 7 6

becomes

0 0 1 1 2 2 3 6
2 2 3 3 6 7 8 8
3 3 5 7 8 9 9 9

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

becomes

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

Rules

You can take the input grid in any convenient format
You may assume the grid values are all non-negative integers in the unsigned 16-bit range (0-65535).
You may assume the grid is a perfect rectangle and not a jagged array. The grid will be at least 2x2.
If you use another algorithm of sorting, you must supply a proof that it will always produce the same resulting order as this particular brand of 2D bubble sorting, no matter what the input is. I expect this to be a non-trivial proof, so you're probably better off using the described algorithm.

Happy Golfing!


Text animation format Code Golf Working with old files from DOS, I found an ancient text animation format, that specify how much time each frame must be shown in the screen. It's very simple:

F1W5F2W3

This example above indicates that Frame 1 must be shown for 5 units of time, and frame 2 for 3 units more. Now I want to convert it to:

1, 1, 1, 1, 1, 2, 2, 2

In the converted example below, frame 1 is repeated 5 times, and frame 2 three times.
Rules: The only allowed letters are F and W (and the lowercase counterparts, f and w). Numbers can go up to 255. Total input String with no more than 255 chars.
Other examples:

Input: F10W3F11W3F10W3F12W3
Output: 10, 10, 10, 11, 11, 11, 10, 10, 10, 12, 12, 12
Input: f1w0f2w10
Output: 2, 2, 2, 2, 2, 2, 2, 2, 2, 2

Short code wins.
Edited - Accepted formats:
Any answer containing the output and ignoring spaces. Ex: 1, 1, 2, 2 or [1,1,2,2] or (1,1,2,2). But NOT 1 1 2 2 or [1; 1; 2; 2] or [1 1 2 2].

Python 3, 57 bytes
lambda s:eval(s.upper().translate({70:'+[',87:']*'})[1:])

Turns a string like
f1w0f2w10

into a expression like
[1]*0+[2]*10

that it evaluated as code. This is done by turning the string uppercase, turning each f into +[ and each w into ]*, and removing the initial +. Thanks to Dennis for saving 7 bytes in Python 3 by using translate with a dictionary.


Create a program that prints the number of characters it has, in words Create a program which prints the amount of characters its source has in English words.

If your program is nine letters long it should print "nine".

Capitalization is ignored: in case you're printing "one" (somehow) you can print "one", "oNe", "ONE" or anything else.

Base ten is required.

Proper spacing is also required.

In the (unlikely but just for specification) case your program reaches one billion characters or more, use the American number scale. A billion here is 10^9 and a million is 10^6.

Do not use "one hundred and one": use "one hundred one".

Do not use the hyphen. Print forty four, not forty-four.

Test cases with a fake program:

10.(96 0s later)..01 prints one HuNdreD ONE -- okay: proper spacing, no "and"
10.(96 0s later)..01 prints one HuNdreDONE -- not okay: wrong spacing
10.(96 0s later)..01 prints one thousand two hundred two -- not okay: base 3 rather than base 10
10...(999999996 0s later) prints nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-six: not okay, wrong number and includes hyphens

Golfy challenge, as always: shortest code wins. You're free to post after the green tick has been given, though. This serves more for completeness for hard to program languages. Malbolge, anyone?

Poetic, 400 bytes
Type fourhundred chars? I say, I think I have an angle.
I say "Gosh, could I just go create some poem? Clearly it comes a long way, writing stuff I say."
I compose the entire written poem, and someone reads a tiny, tiny portion.
"Surely, it all is garbage," cried a big fat crybaby.
Would HE frankly notice how many long, tedious hours I took?
The crybaby whined a lot. I watched, then I ignored him.

Try it online!
Prints Four HunDrED. (I tried to make it print some number in the 300s, but I can't seem to do so in under 400 bytes.)
Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.


Longest Common Prefix of 2 Strings Write a program that takes 2 strings as input, and returns the longest common prefix. This is code-golf, so the answer with the shortest amount of bytes wins.

Test Case 1:

"global" , "glossary"
"glo"

Test Case 2:

"department" , "depart"
"depart"

Test Case 3:

"glove", "dove"
""

Python 3, 54 bytes

Thanks Python for having a built-in function for this task! :D

import os;print(os.path.commonprefix(input().split()))

Takes input as two words separated by a space such as glossary global.


Find the absolute value of a number without built-in functions The challenge is to take any real number as input and output or return the absolute value. You may not use any built-in functions other than those dealing with input and output/returning. This is code golf, so the shortest code wins. This is my first question here, so bear with me if I've left something obvious out of the challenge.

As per Quincunx's suggestion, I am limiting input to anywhere between -9E99 and 9E99.

Also, the only functions/operators you can use are input, output, return, +, -, *, /, %, ^ +=, -=, *=, /=, >, <, ==, >=, <=, !=, square, and square root or their equivalents

J, 2 bytes

**

Usage:

   f =: **
   f 9.3
9.3
   f -9.3
9.3

Explanation:

This uses the * verb in both its monadic and dyadic forms. The monadic form returns -1 if it's given a negative number, 0 if it's given 0 and 1 if it's given a positive number. The dyadic form is just plain old multiplication. Putting them in a function literal turns them into a hook which gets evaluated like this: y * (*y).


Composite Factorization This is similar to prime factorization, where you find the smallest prime factors of a number (i.e. 8 = 2 x 2 x 2). But this time, you are to return an array/list of the smallest composite factors of any given positive integer n. If n is prime, simply return an empty list.

Examples:

Prime:

n = 2
Result: []

Composite and Positive:

n = 4
Result: [4]

n = 32
Result: [4, 8]

n = 64
Result: [4, 4, 4]

n = 96
Result: [4, 4, 6]

Rules:

The product of the factors in the list must equal the input
Standard loopholes are banned
An array/list must be returned or printed (i.e. [4])
Your program must be able to return the same results for the same numbers seen in the examples above
The factors in the array/list can be strings so [4] and ["4"] are both equally valid
A prime number is any positive integer whose only possible factors are itself and 1. 4 returns [4] but is not prime since 2 is also a factor.
A composite number for this challenge any positive integer that has 3 or more factors (including 1) like 4, whose factors are 1, 2, and 4.

Clarifications:

Given a number such as 108, there are some possibilities such as [9, 12] or [4, 27]. The first integer is to be the smallest composite integer possible (excluding 1 unless mandatory) thus the array returned should be [4, 27] since 4 < 9.
All factors after the first factor need to be as small as possible as well. Take the example of 96. Instead of simply [4, 24], 24 can still be factored down to 4 and 6 thus the solution is [4, 4, 6].

Winning Criteria:

Shortest code wins since this is code-golf.

Jelly, 12 bytes

»0Æf×Ṫ$-¦×2/

Try it online!

How it works

»0Æf×Ṫ$-¦×2/  Main link. Argument: n

»0            Take the maximum of n and 0.
              Jelly's prime factorization does weird things for negative numbers.
  Æf          Take the prime factorization of the maximum.
        ¦     Conditional application:
    ×Ṫ$         Pop the last element of the array and and multiply all elements
                of the remaining array with it.
       -        Replace the element at index -1 with the corresponding element in
                the result.
              This effectively multiplies the last two elements of the array.
         ×2/  Multiply the factors in non-overlapping pairs. If the last element
              does not have a partner, leave it unmodified.


Draw Reutersvärd's Triangle This impossible object is Reutersvärd's triangle:

Draw your own version according to these rules:

Exactly 9 cubes total
Each side is made up of exactly 4 cubes
The cubes appear to overlap such that the rendered object is in fact an impossible object
4 distinct colours are used - one for the background and 3 for each of the faces of the cubes
In bitmap output, the full triangle should be at least 100 pixels tall and at least 100 pixels wide
Aspect ratio: the width and height of the full triangle should not be off by more than a factor of 2
The triangle may be rotated by any amount relative to the above image
The triangle may or may not be reflected relative to the above image

Mathematica, 237 bytes

n={-1,1}#&;c_~g~s_:=Polygon[c+s#&/@{k={12,9},m=n@k,t={0,-12}}];p={#,#2~g~1,#3~g~-1}&;a=p[Cyan,#-k,#+m]&;b=p[Blue,#-t,#+k]&;c=p[Red,#-m,#+t]&;Graphics@{{a@#,b@#,c@#}&/@{j=4k,s=4{4,9},n@s,4m,r={-32,8},q=-4{4,5},4t,n@q,n@r},a@j,b@s,c@j,c@s}

Easier-to-read version:

1  n = {-1, 1} # &;
2  c_~g~s_ := Polygon[c + s # & /@ {k = {12, 9}, m = n@k, t = {0, -12}}];
3  p = {#, #2~g~1, #3~g~-1} &;
4  a = p[Cyan, # - k, # + m] &;
5  b = p[Blue, # - t, # + k] &;
6  c = p[Red, # - m, # + t] &;
7  Graphics@{
8    {a@#, b@#, c@#} & /@
9      {j = 4 k, s = 4{4, 9}, n@s, 4 m, r = {-32, 8},
10       q = -4{4, 5}, 4 t, n@q, n@r},
11   a@j, b@s, c@j, c@s}

Line 1 defines a function n that negates the first coordinate of an ordered pair. Line 2 defines a function g that produces a (roughly) equilateral triangle centered at the point c, and pointing down or up depending on whether s is 1 or -1. Line 3 defines p to be a parallelogram template consisting of a color and two triangles, and lines 4–6 define a, b, and c to be the three different specific types of parallelograms that appear in the cubes.

Line 8 defines a function {a@#, b@#, c@#}& that draws an entire cube centered at the point #; lines 9 and 10 apply that to the nine points needed to make the larger triangle. This produces nine cubes, starting at the upper right and going counterclockwise, where the later ones cover up parts of the earlier ones. Finally, line 11 redraws four parallelograms (in the upper right of the picture) so that they end up covering the later cubes as they're supposed to. The output is below:


Implement half away from 0 rounding Overview:

Using you language of choice, implement a complete "half away from 0" rounding function in the shortest amount of code possible.

Rules/Constraints:

Direct, predefined Round-like functions are not allowed.
Floor/Ceiling-type functions are allowed, if your language supports these.
Function shall be able to handle 32-bit floating-point values.
Function shall be able to correctly handle negative values (see examples).
This is Golf, so shortest code wins.
Correct rounding for this challenge is to round away from 0, such that a rounded value will have an equal or larger absolute value.

Input/Output:

Your function shall take two parameters:

The first is a float x, which is the value to round.
The second is an integer n, which is the number of decimal places to round to.
x can be a whole number or contain a decimal part, fitting within a 32-bit, single-precision float.
n can be greater than or equal to 0, and may be larger than the number of decimal places in x.

Output will be the correctly rounded x.
*In cases where the solution is not exactly representable in IEEE float format, the output should be the logical representation you would have figured if not using a computer. i.e. The output of Round(0.125, 2) should be 0.13.

Example I/O:

Round(1.23456789, 7)
1.2345679

Round(1.234, 5)
1.234 OR 1.23400 (Your choice on trailing 0)

Round(-0.5, 0)
-1 NOT 0

Round(-0.123, 2)
-0.12 NOT -0.13

Round(3.1415926535897932384626433832, 20)
3.14159265358979323846

Winning:

**Some system limitations may be present which make your function less accurate/usable. In these cases, supply the best possible calculation you can within those limitations.

For example, I have a solution in my preferred environment, VBA in Office 2003, which only allows me to round up to 307 digits, while the IDE will only let me use values up to 15 significant decimal places. (I will eventually post this example here.)

With your answer submission, please post the highest values of n and the largest number of significant decimal digits for x for which your function will run. If you cannot meet the minimum requirements, that solution is disqualified, no matter the code length. (i.e. my own solution described above is invalid)

While this is code golf, and the shortest code will generally win. If two answers exist with different maximum values for x and n, the solution which works with the highest input values (measured as x * n) will win. If these two solutions meet the same limitation while fulfilling the requirements of the challenge, then the shortest code of those two will win.

If no solutions meet the requirement, then the best limitation score (shortest code length in the event of a tie) will win.

Example submission given the rules above for my own code:

<CODE HERE>
Max n = 307
Max x digits = 15
Limitation Score (x * n) = 4605

Q (29 Characters)

{("i"$x*10 xexp y)%10 xexp y}

Sample usage

{("i"$x*10 xexp y)%10 xexp y}[1.23456;4]

Works by multiplying your x input by 10 to the power of your y input, casting to an int and then dividing again by 10 to the power of your y input.


Let the trigonometry begin! Introduction:

The sine of x is given by the formula:

sin(x) = x - x^3/3! + x^5/5! - x^7/7! + x^9/9! - x^11/11! // and more follows...

The cosine of x is given by the formula:

cos(x) = 1 - x^2/2! + x^4/4! - x^6/6! + x^8/8! - x^10/10! // and more follows...

Task:

Given the value of x and n, write a program (no functions, etc.) to output the value of sin(x) and cos(x) correct upto n terms of the formula above. Assume that x is in radians.

Input:

x n

A decimal number x (with upto 3 decimal places) and an integer n. Input must be on stdin or a prompt dialog box (iff your language doesn't support stdin)

Output:

[sin(x)]
[cos(x)]

The value of both sin(x) and cos(x) should be rounded to 6 decimal places. If sin(x) is 0.5588558855 (10 decimal digits), it should be rounded to 0.558856 (6 decimal digits). The rounding must take place to the nearest, as described in the fifth column, "Round to nearest", of the the table in this Wiki article.

Constraints:

1 <= x <= 20
1 <= n <= 20

Samples:

----
5 3

10.208333
14.541667
----
8.555 13

0.765431
-0.641092
----
9.26 10

-3.154677
-8.404354
----
6.54 12

0.253986
0.967147
----
5 1

5.000000
1.000000
----
20 20

-5364.411846
-10898.499385
----

Notes:

Standard loopholes are prohibited.
Built-in math functions and operators of trigonometry (sin, cos, tan, etc.), factorial, and exponentiation cannot be used. You are free to use a built-in rounding function for estimating the result of computing sin(x) and cos(x) to the 6-th decimal digit.
No need to handle wrong inputs.
Only ASCII characters can be used in the program, not the Chinese Unicode ones that allow code compression.
Your program must terminate, and display the output, within 3 seconds of input.
Your answer must accompany the ungolfed code, along with the explanation of the code (compulsory if the code is not immediately obvious to programmers-not-familiar-with-your-language, especially GolfScript, J, etc.).
Please include a link to an online compiler where your program can be tested.

Scoring:

The answer with lowest code length in characters, including white space, tabs, etc.  wins! Winner would be declared on 21 May 2014.

EDIT: 21/05/14
Winner is aditsu using CJam language. Runner up follows jpjacobs with J language, and second runner up is primo with Perl language. Congrats all!

Perl - 72 bytes

$~=<>=~$"+$'*2;$_=1-$_*$`/$~--/$~*$`for($,,$;)x$';printf'%f
%f',$`*$,,$;

Or, counting command line options as 1 byte each, in 70 bytes:

#!perl -n
$-=/ /+$'*2;$_=1-$_*$`/$---/$-*$`for($,,$;)x$';printf'%f
%f',$`*$,,$;

Or, if you'll allow me Perl 5.8, in 63 bytes:

#!perl -p
$.+=$'<</ /;$_=1-$_*$`/$.--/$.*$`for($_=$#='%f
',$\)x$';$_*=$`

but why would you.

Edit: Compliance with the new rules. %f rounds to 6 places by default, how convenient!

Algorithm

Examining the Taylor series for sin(x):

it can be seen that each term evenly divides every successive term. Because of this, it can be transformed rather effortlessly into a nested expression:

cos(x) transforms similarly, without the leading x, and denominator terms one smaller.

Additionally, this nested expression can be reformulated as a reverse recursive expression:

with s∞ = 0 and sin(x) = x·s1, which is ultimately what is used.

Ungolfed

<> =~ m/ /;          # read one line from stdin, match a space
                     # prematch ($`) is now x, postmatch ($') is now n
($x, $n) = ($`, $'); # reassign, for clarity
$i = 2*$n + 1;       # counting variable (denominators)

for (($s, $c)x$n) {  # iterate over $s and $c, n times each
  # compute the next term of the recursive expression
  # note: inside this loop $_ is not the _value_
  # of $s and $c alternately, it _is_ $s and $c

  $_ = 1 - $_ * $x**2 / $i-- / $i;
}

# formated output
printf("%f\n%f", $x*$s, $c);

Sample Usage

$ echo 5 3 | perl sin-cos.pl
10.208333
14.541667

$ echo 8.555 13 | perl sin-cos.pl
0.765431
-0.641092

$ echo 9.26 10 | perl sin-cos.pl
-3.154677
-8.404354

$ echo 6.54 12 | perl sin-cos.pl
0.253986
0.967147

$ echo 5 1 | perl sin-cos.pl
5.000000
1.000000

$ echo 20 20 | perl sin-cos.pl
-5364.411846
-10898.499385

If you want to test this online, I recommend using compileonline.com. Copy-Paste the code into main.pl, and the input into the STDIN box, then Execute Script.


Measuring a pile of logs Introduction

This is a log of length 5:

#####

I want to pile a bunch of these logs on top of each other.
How I do this is that I slide a new log onto the topmost one from the right, and stop sliding when their left or right ends align (don't ask why).
If the new log is longer, it slides all the way to the left end of the topmost log:

########  <-
#####

If it is shorter, it only slides until their right ends align:

  ######  <-
########
#####

As I slide more logs into the pile, their positions are determined by the current topmost log:

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

This looks physically impossible, but let's pretend it works.

The task

Your input shall be a non-empty list of positive integers, representing the lengths of my logs.
The leftmost number is the first log I put to the pile, so it ends up at the bottom.
In the above example, the input would be [5,8,6,2,4,3,6,2].
Your output shall be, for each column of the resulting pile, the number of logs that cross that column.
In the above example, the correct output would be [2,2,3,3,3,2,4,6,3,3,1,2,2].

Rules and scoring

Input and output can be in any reasonable format.
The output can only contain positive integers, i.e. it must not have leading or trailing 0s.
Normal code-golf rules apply: you can write a full program or a function, the lowest byte count wins, and standard loopholes are forbidden.

Test cases

[1] -> [1]
[4] -> [1,1,1,1]
[3,2] -> [1,2,2]
[2,3] -> [2,2,1]
[2,2,2] -> [3,3]
[2,3,2] -> [2,3,2]
[3,2,3] -> [1,3,3,1]
[1,3,2,2,1,3,1] -> [2,3,5,1,2]
[4,3,4,2,4,3,4,2] -> [1,3,3,5,5,3,4,2]
[5,8,6,2,4,3,6,2] -> [2,2,3,3,3,2,4,6,3,3,1,2,2]
[5,10,15,1,1,1,1,1,2] -> [3,3,3,3,3,2,2,2,2,2,1,1,1,1,7,1]
[13,12,2,10,14,12] -> [1,2,2,2,2,2,2,2,2,2,2,5,5,3,3,3,3,3,3,3,3,2,2,2,2]
[12,14,3,6,13,1,1] -> [2,2,2,2,2,2,2,2,2,2,2,5,4,4,2,2,2,1,1,1,1,1,1,3]
[7,5,12,5,1,10,14,5] -> [1,1,3,3,3,3,3,1,1,2,2,2,2,5,2,2,2,2,2,2,2,2,3,2,2,2,2]
[14,5,1,3,12,6,2,2,1,7,9,15] -> [1,1,1,1,1,1,1,1,1,2,2,2,2,5,2,2,1,1,1,2,2,2,2,4,8,3,3,3,3,3,3,2,2,1,1,1,1,1,1]

Jelly, 19 13 bytes

IN0»0;+\+"RṬS

Try it online!

Saved 2 bytes thanks to @Jonathan Allan.

Explanation

IN0»0;+\+"RṬS  Input: array A
I              Increments
 N             Negate
  0»           Max with 0
    0;         Prepend 0
      +\       Cumulative sum
        +"     Vectorized add with
          R    Range, vectorizes over each integer
           Ṭ   Create a list with 1's at the specified indices
            S  Sum


Generate Programs in Increasing size In this challenge, you will write a program which outputs a program which is the double the length of the original program. The outputted program should output a new program a program double its length.

Examples

If my program is a:

< a
> aa

< aa
> aaaa

< aaaa
> aaaaaaaa

Rules

No quine built-ins
The original program must be at least one byte
The sequence should theoretically work infinitely
Your program is not allowed to read from anything (file, stdio)

Your score is the size of the original program.

CJam, 10 bytes

{"_~"+_}_~

Test it here.

Explanation

{"_~" e# Generalised quine framework, leaves the block and the string "_~"
      e# on the stack.
+     e# Prepend the block to the string.
_     e# Duplicate the resulting array.
}_~