Reduce a number by its largest digit Task:

Given an integer number in decimal number system, reduce it to a single decimal digit as follows:

Convert the number to a list of decimal digits.
Find the largest digit, D
Remove D from the list. If there is more than one occurrence of D, choose the first from the left (at the most significant position), all others should remain intact.
Convert the resulting list to a decimal number and multiply it by D.
If the number is bigger than 9 (has more than 1 decimal digit), repeat the whole procedure, feeding the result into it. Stop when you get a single-digit result.
Display the result.

Example:

26364 ->
1. 2 6 3 6 4
2. The largest digit is 6, so D=6
3. There are two occurrences or 6: at positions 1 and 3 (0-based). We remove the left one,
    at position 1 and get the list 2 3 6 4
4. we convert the list 2 3 6 4 to 2364 and multiply it by D:
   2364 * 6 = 14184
5. 14184 is greater than 9 so we repeat the procedure, feeding 14184 into it.

We continue by repeating the procedure for 14184 and so on and we go through the following intermediate results, finally reaching 8:

11312
3336
1998
1782
1376
952
468
368
288
224
88
64
24
8

So the result for 26364  is 8.

Input: An integer / a string representing an integer

Output: A single digit, the result of the reduction applied to the number.

Test cases:

9 -> 9
27 -> 4
757 -> 5
1234 -> 8
26364 -> 8
432969 -> 0
1234584 -> 8
91273716 -> 6

This is code-golf, so the shortest answers in bytes in each language win.

05AB1E, 6 bytes

Code:

[Dg#à*

Uses the 05AB1E encoding. Try it online!

Explanation

[Dg#     # While the length of the number is not 1
    à    # Extract the largest element from the current number
     *   # Multiply it with the leftover number


Japanese pitch accent numbers Your challenge is to turn a Japanese word and a dictionary pitch accent number into a new string where the rises and falls in pitch are marked: e.g. (2, ウシロ) → ウ/シ\ロ.

  To help you out with this, I'll explain a little about Japanese phonology.

Background: on moras

For the purpose of this challenge, we will write Japanese words in katakana, the simplest Japanese syllabary. A word consists of one or more moras, each of which consists of

one of:

アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンッガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ

optionally followed by one of:

ャュョ

For example, シャッキン consists of 4 moras: シャ, ッ, キ, ン.

※ The three optional characters are small versions of katakana ヤユヨ (ya yu yo).　 For example, キャ is ki + small ya, pronounced kya (1 mora), whereas キヤ is kiya (2 moras).

Background: pitch accents

Japanese words are described by a certain contour of high and low pitches. For example, ハナス (hanasu, speak) is pronounced

   ナ
  /  \
ハ    ス–···

meaning the pitch goes up after ハ ha, then falls after ナ na, and stays low after ス su.(That is to say: Unaccented grammar particles after su will be low again).

We might describe this contour as “low-high-low-(low…)”, or LHL(L) for short.

In a dictionary, the pitch of this word would be marked as 2, because the pitch falls after the second mora. There are a few possible pitch patterns that occur in Tōkyō dialect Japanese, and they are all given a number:

0, which represents LHHH…HH(H). This is heibangata, monotone form.

   イ–バ–ン–···                ···
  /                  or       /
ヘ                          ナ

1, which represents HLLL…LL(H). This is atamadakagata, “head-high” form.

イ                          キ
  \                  or       \
   ノ–チ–···                   ···

n ≥ 2, which represents LHHH… (length n) followed by a drop to L…L(L).For example, センチメエトル has pitch accent number 4:

   ン–チ–メ
  /       \
セ         エ–ト–ル–···

Such a word must have ≥ n moras, of course.

※ Note the difference between ハシ [0] and ハシ [2]:

   シ–···                シ
  /            vs       /  \
ハ                    ハ     ···

You can hear the different pitch accent numbers demonstrated here ♪.

The challenge

Given an integer n ≥ 0 (a pitch accent number as above) and a valid word of at least n moras, insert / and \ into it at points where those symbols would occur in the diagrams above; i.e. at points in the word where the pitch rises or falls.

The output for (2, ハナス) would be:

ハ/ナ\ス

And the output for (0, ヘイバン) would be:

ヘ/イバン

Remember: you must correctly handle sequences like キョ or チャ as a single mora. The output for (1, キョウ) is キョ\ウ, not キ\ョウ.

  Instead of / and \, you may pick any other pair of distinct, non-katakana Unicode symbols.

This is code-golf: the objective is to write the shortest solution, measured in bytes.

Test cases

One per line, in the format n word → expected_output:

0 ナ → ナ/
0 コドモ → コ/ドモ
0 ワタシ → ワ/タシ
0 ガッコウ → ガ/ッコウ
1 キ → キ\
1 キヤ → キ\ヤ
1 キャ → キャ\
1 ジショ → ジ\ショ
1 チュウゴク → チュ\ウゴク
1 ナニ → ナ\ニ
1 シュイ → シュ\イ
1 キョウ → キョ\ウ
1 キャンバス → キャ\ンバス
2 キヨカ → キ/ヨ\カ
2 キョカ → キョ/カ\
2 ココロ → コ/コ\ロ
2 ジテンシャ → ジ/テ\ンシャ
3 センセイ → セ/ンセ\イ
3 タクサン → タ/クサ\ン
4 アタラシイ → ア/タラシ\イ
4 オトウト → オ/トウト\
6 ジュウイチガツ → ジュ/ウイチガツ\

Generated by this reference solution.

Retina 0.8.2, 68 bytes (UTF-8)

\d+(.[ャュョ]?)
$1/$&$*1\
/1\b

/.
/
+`1(1*.)(.[ャュョ]?)
$2$1

Try it online! Link includes test cases. Explanation:

\d+(.[ャュョ]?)
$1/$&$*1\

Convert the number to unary, wrap it in /\, and insert it after the first mora.

/1\b

If the number was 1, then delete it and the /, leaving the \.

/.
/

Subtract 1 from the number, but in the case of 0, this deletes the \, leaving the /.

+`1(1*.)(.[ャュョ]?)
$2$1

Move the \ one mora to the right for each remaining 1.


Build a drug testing scheduler In this problem on Puzzling.SE, I ask a question about determining the amounts of drug to use in a clinical test to minimize total drug usage and fulfill the requirements of the testing procedure.
The problem is as follows, for those of you who currently don't have access to the private beta:

A medical researcher is trying to test the effect of a certain drug on mice. He is supposed to collect data for all doses from 1 to 2N units, but only has the data collection resources for N tests. He has decided to only test dose amounts that are not multiples or factors of each other (for example, if he decided to use a dose of 15 units for a specific test, that would preclude tests for 1, 3, 5, 30, 45, etc. units). Moreover, because the drug is relatively expensive, he wants to use as little of the drug as he can manage to run these tests.
How can he arrange the dosage amounts so that he ends up using all N test packages, and the total units of dosage used in the tests are as low as possible?

The original problem states N = 25. Your task is to build a program than can answer this question for any number of tests up to N = 2500.
Your program will take a number N from 1 to 2500 as input, and return a set of N integers between 1 and 2N inclusive such that none of the N numbers are multiples of each other, each number from 1 to 2N is a factor or multiple of at least one of the numbers in the set, and the sum of all the numbers in the set is as low as you can manage.
Your program must return a valid result for each value of N to be valid.
Your program will be scored by the sum of all the returned numbers for each scenario from N = 1 to N = 2500. In the event of a tie, the shorter solution will win.

Javascript 5,955,958,211

I'm not sure if it is the optimal solution.
I used a brute-force method.

function f(n) {
  var o=[];
  for(var i=n;i--;) o.push(2*n-i); //init array from n+1 to 2*n

  for(i=n;i>0;i--) { //bruteforce on number from n to 1
    var index=0;
    var nbFactor=0;
    for(j=0;j<n;j++) {
      if((o[j]/i)%1==0) {
        index=j;
        nbFactor++;
      }
    }
    if(nbFactor==1) { //if there is only 1 factor, replace it by the new number
      o[index]=i;
    }
  }
  return o.sort(function(a,b){return a-b;});
}

Golfed (130) :

function f(n){o=[];for(i=n;i++<2*n;)o.push(i);for(i=n;i;i--){for(d=c=j=0;j<n;j++)if((o[j]/i)%1==0)d=j,c++;if(c==1)o[d]=i}return o}

Here is the result found by my algorithm for 25 :

  [8, 12, 14, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29, 30, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]

Little piece of code to compute the score (takes approx. 200 seconds on Chrome) :

var result=0;
var t = Date.now();
for(var j=1;j<2501;j++) {
  result += f(j).reduce(function(r,e){return r+e;});
}
console.log("Score : " + result + "\nCompute time : " + ((Date.now()-t)/1000) + " seconds");


Are All the Items the Same? Given a list of non-negative integers, return whether or not that list is all the same number.
Rules

Input and output can be taken/given in any reasonable and convenient format
Truthy/Falsey values can be represented as any value of your choice as long as it's reasonable and relatively consistent (e.g. 1 for falsey and >= 2 for truthy is fine)
There will always be at least 1 item in the input list
The list items are guaranteed to be in the range [0, 9] (\$0 \le n \le 9\$)
Standard loopholes apply

This is code golf, so the shortest program in each language wins. I've made a community wiki answer for trivial answers, so feel free to submit potentially longer programs.
Test Cases
[1, 1, 1, 1, 1, 1, 1] -> True
[1, 2, 3, 4] -> False
[6, 9, 6, 9, 6] -> False
[6] -> True
[7, 7] -> True
[4, 2, 0] -> False

Trivial Built-in Answers
This is the post for all of the languages where this is a built-in
Vyxal, 1 byte
≈

Try it Online!
Jelly, 1 byte
E

Try it online!
05AB1E (legacy), 1 byte
Ë

Try it online!
Wolfram Language (Mathematica), 5 bytes
Equal

Try it online!
SameQ also works.
Brachylog, 1 byte
=

Try it online!
Husk, 1 byte
E

Try it online!
Factor, 3 bytes
std

Try it online!
Outputs 0.0 if they're the same, or something else if not. all-eq? and all-equal? are longer built-ins that output booleans. all-equal? uses = (ordinary equality) and all-eq? uses eq? (strict object reference equality), but they behave the same for integers.


Recover the mutated source code (for robbers) This is the companion thread to the main Recover the mutated source code (link) challenge. If you have successfully cracked a cop's answer, post your solution as an answer to this question.

As a reminder, here are the robber rules from the main challenge again:

  The robber will attempt to change the cop's program (which completes
  Task #1) into a program that completes Task #2 (not necessarily the
  original program written by the cop) in the edit distance specified by
  the cop.

  An already-cracked submission cannot be cracked again (only the first
  robber who cracks a submission gets credit).

  After cracking a submission, please do the following:

  Post an answer to this challenge's accompanying question (link), providing the language, your solution, and a link to the original answer.
  Leave a comment with the text "Cracked" that links to your posted answer.
  Edit the cop's answer if you have edit privileges (if you do not, either wait until someone else with the required privileges does
  so for you or suggest an edit).

And scoring:

  If a robber successfully cracks a cop's submission, the robber's score goes up by the edit distance of that submission. For example, a robber that cracks a submission with an edit distance of 3 and one with a distance of 5 earns 8 points. The robber with the highest score wins. In the event of a tie, the robber who earned the score first wins.

Leaderboard

There are no cracked submissions yet.

Python 2, FryAmTheEggman
x=n=1;j=input();
while j>2:
    x,n=n,x+n;j-=1;
    ##while~-all(n%i for i in range(2,n)):n+=1;
print n

Used 12 edits. Put in an extra # to make it 13.


Tips for Golfing in Go What general tips do you have for golfing in Go? I'm new to Code Golfing and looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Go.

Please keep to one tip per answer.

Inspired by @EMBLEM's answer here.

You can put a package's functions in the global namespace when you import them like so:

package main

import ."fmt"

func main() {
    Printf("Hello World!")
}


Where will your buddies sit? You and some buddies are going bowling. There are a total of N bowlers. However, there are only N-1 chairs to sit in. The solution is simple: whoever's turn it currently is doesn't get a chair. Then when their turn is over, they sit in the chair of the person that goes next.

Lets take an example. Say You are named A, and your four friends are named B, C, D, and E. Every player moves in alphabetical order, so you get to go first. Since there are 5 players, there are only 4 seats. Your friends sit in the four seats in this order:

  CEBD

You go, and yay you get a strike! It's B's turn next, so you sit in his chair. Now it looks like this:

  CEAD

B goes. Gutterball! Then he sits in C's spot, and C goes next turn.

  BEAD

then C sits in D's chair.

  BEAC

and D sits in E's chair

  BDAC

and lastly, E sits in your chair.

  BDEC

You'll notice that now everybody's seat is (pseudo) shuffled. You must find out, after X turns, who will be sitting where?

Input

Your program must take two inputs from the user, a string and a number. No prompts are needed. The string will be 1-51 alphabetic characters (B-Z and a-z) with no repeats. This represents the order your friends chose to sit. There will be no uppercase A because that is you, and you always go first. The number will be the total number of rounds (not games) that you and your friends play. This number will be positive and reasonably sized (less than 1000).

Output

Your program must print out the order your friends are sitting in after X turns, and whose turn it is. So for example, if after X turns the order was BEDGCAHF and it was Z's turn, your program must print exactly this:

BEDGCAHF
It is Z's turn.

Here are a few sample input and outputs.

input: E, 4
E
It is A's turn.

input: E, 5
A
It is E's turn.

input: Bb, 2
AB
It is b's turn.

input: dgOPZXKDQYioHflFhpqzUsSaeILwckVNEtGTCJBvnruRyWMmjxb, 999
JNuvFDqjwEPVnMSlOWXgAZyGKordIRBtkamziphcUYbxfCsTQeH
It is L's turn.

Rules

Everybody goes in alphabetical order, with capital letters taking precedence over lower case.
This is code-golf, so standard loopholes apply, and submissions are scored in bytes.

Pyth, 39 38 bytes
L@+\ASzbuXGyhHyHQzpyQ"It is ""'s turn.

This is based around repeated applications of the find and replace operation, X. The first bit defines a lookup function, y, which finds the bth player in the player order. Then, we repeatedly perform substitutions to find the final seating order, and finally print out whose turn it is.
Amusingly, the code to find the final seating order is shorter (18 bytes) than the code to print whose turn it is (21 bytes).
The code takes the seating string on the first line of STDIN, and the number of turns on the second.
Demonstration.
Explanation:
L@+\ASzbuXGyhHyHQzpyQ"It is ""'s turn.
                                          Implicit:
                                          z = input()
                                          Q = eval(input())

L                                         def y(b): return
  +\ASz                                    "A" + sorted(z)
 @     b                                  (               )[b]
        u       Qz                        reduce for H in range(len(Q)),
                                          G starts as z.
         XGyhHyH                          replace in G y(H+1) with y(H).
                  pyQ"It is ""'s turn.    Print out whose turn it is.


Finding "sub-palindromes". The shortest code that finds all unique "sub-palindromes" of a string, that is: any substring with length > 1 that is a palindrome.

eg.1

input: "12131331"
output: "33", "121", "131", "313", "1331"

eg.2

input: "3333"
output: "33", "333", "3333"


Smallest Lua table copy So I really like to mess with tables and shallow and deep copies and I can do it in 239 chars! I wonder if there's a shorter way to do it...

Rules:

It must be done in less than 239 chars.
You must set table.copy.shallow and table.copy.deep.
A deep copy must maintain recursion. (so if I had tx.t == tx, a deep copy must have ty.t == ty (where ty is a deep copy of tx))
You must make a local copy of every function you use. (for speed)
You must be able to pass in a custom recursion table with a metatable to override default copy behavior. (at least on the deep copy function, see examples here)
If needed, use metatables. If possible, abuse them.
It must work in Lua 5.1 and 5.2.
You may use load/loadstring.
You may use the C API.
Some input/output examples (actually unit test): https://gist.github.com/SoniEx2/7942bdd0658b719ab275

235

Substantially based on the guts of SoniEx2's 239 answer.

local o,k,F=type,next,{}for n=0,2 do
F[n]=function(a,r,t,G)if n<1 or o{}~=o(a)then return a end
t={}r=r or{}r[a]=n<2 and t G=F[n%2]for x,y in k,a do
t[r[x]or G(x,r)]=r[y]or G(y,r)end
return t end end
table.copy={shallow=F[2],deep=F[1]}

The advantage comes from using the same function prototype for both functions. Instantiating the same function prototype with different upvalues allows it to fill both roles.

Ungolfed:

-- ungolfed
-- note that type and next must have local copies to meet the spec
local o, k, F = type, next, {}
for n = 0, 2 do
  -- F[0] will be the identity function
  -- F[1] will be table.copy.deep
  -- F[2] will be table.copy.shallow
  F[n] = function(a, r, t, G)
    -- a is the table input
    -- r is the optional "custom recursion table" that is required
    -- t and G are just locals
    -- the spec implies (but does not state) that the global environment shouldn't be polluted
    -- r will only be used by recursive calls

    -- if n < 1, this is F[0], so act is the identity
    -- o is type, o{} is "table"
    -- if a is not a table, just return it
    if n < 1 or o{} ~= o(a) then
      return a
    end

    -- t will be the copy
    t = {}

    -- r will be the map that remembers which tables in the original map to which tables in the copy
    -- or, if it is passed in, it is a table that controls the behavior of the copy
    r = r or {}

    -- F[0] doesn't each here
    -- F[1] must add t to the map
    -- F[2] must not add t to the map
    -- (adding false will not hurt F[2] -- only true values will be picked up below)
    -- (behavior may not be exactly as desired for shallow copy, but spec doesn't require this feature)
    r[a] = n < 2 and t

    -- this is the function we will call to copy members
    -- for F[1] table.copy.deep, this is F[1] itself
    -- for F[2] table.copy.shallow, this is F[0] the identity
    -- (for F[0], we never get this far)
    -- the byte count seems equivalent making this a local vs putting it
    -- in both places it is used, but this is probably more efficient
    G=F[n%2]

    -- loop over and copy members
    -- first try r (which will only have non-1 entries for tables in F[1])
    -- then try G
    -- note that instead of calling "pairs" as usual, we can observe that pairs(a)
    -- is defined to return next, a, nil -- we use these (with implicit nil) directly
    for x, y in k, a do
      t[r[x] or G(x,r)] = r[y] or G(y,r)
    end

    return t
  end
end

-- export the functions as required
table.copy = {
  shallow = F[2],
  deep = F[1]
}

Hopefully I understood the spec correctly. This passes the provided test cases and there is enough similarity in the construction that I'm reasonably sure it does the same thing.

Note -- Initially I didn't understand the part about the "custom recursion table", but I have edited my answer to support it.

Note 2 -- Improved answer. I've also decided that the provided reference solution in 239 bytes does not exactly match my understanding of how the custom recursion table ought to work, since it cannot be used to add false into the copy. However, I believe my solution works as well as the provided one.


A sign showing grouped opening hours of a cafe You have probably seen these signs on the doors of various shops:

  OPENING HOURS

  mon-fri 0900-1800
  sat-sun 1100-1530

The task here is to generate a sign like that, grouping consecutive days with the same opening hours, from a list of opening hours for the whole week. Note that the week "wraps around" for what is considered consecutive.

Input:

7 elements, representing the opening hours for each day in a week, starting with Monday.
Each element is a string, on the form XXXX-XXXX
Example input:

0900-1800 0900-1800 0930-1730 0930-1730 0900-1500 1100-1500 1100-1500

It's ok to send the input as an array (for instance as input to a function if you don't read from stdin)

Output:

A list of opening hours, where consecutive days with the same opening hours are shown as a range. Note that sunday (the last day) and monday (the first day) also are consecutive days.
A day where the day doesn't have similar opening hours to the days before or after is printed by itself
Days are specified as three lowercase letters: mon tue wed thu fri sat sun
Remember that first element in the input corresponds to mon, next to tue etc.
Opening hours are shown as in the input
Two examples

mon-fri 0900-1800, sat-sun 1100-1500
mon-wed 1030-1530, thu 100-1800, fri-sun 1200-1630

The output should be sorted, so ranges appear in the order the days do in the week. Monday is preferred to be first, but it may happen it is not first in a group because the week wraps. So in this case tue is the first range.

tue-fri 0900-1800, sat-mon 1100-1500

Don't group unless consecutive, here wednesday and friday have same opening hours but are separated by a Thursday with different opening hours so they are listed by themselves.

mon-tue 1000-1200, wed 0900-1500, thu 1000-1800, fri 0900-1500, sat-sun 1000-1500

The output can be either comma-separated as the examples here, or separated by a newline as in the example on top.

Test cases

First line is input, second line is expected output

0900-1800 0900-1800 0900-1800 0900-1800 0900-1800 1100-1500 1100-1500
mon-fri 0900-1800, sat-sun 1100-1500

0900-1800 0900-1800 0900-1800 0930-1700 0900-1800 1100-1500 1100-1500
mon-wed 0900-1800, thu 0930-1700, fri 0900-1800, sat-sun 1100-1500

1100-1500 0900-1800 0900-1800 0900-1800 0900-1800 1100-1500 1100-1500
tue-fri 0900-1800, sat-mon 1100-1500

1100-1500 1100-1500 0900-1800 0900-1800 0900-1800 0900-1800 1100-1500
wed-sat 0900-1800, sun-tue 1100-1500

1200-1500 1100-1500 0900-1800 0900-1800 0900-1800 0900-1800 1100-1500
mon 1200-1500, tue 1100-1500, wed-sat 0900-1800, sun 1100-1500

Rules

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

JavaScript (ES6), 182 173 170 163 157 bytes

Saved 6 bytes with the help of edc65

Takes input as an array of strings and directly prints the result to the console:

h=>{for(D="montuewedthufrisatsun".match(/.../g),d=c=i=j=0;j<8;y=d)h[i]==h[6]?i++:(v=h[d=(i+j++)%7])!=c&&(j>1&&console.log(D[x]+(x-y?'-'+D[y]:''),c),x=d,c=v)}

Formatted and commented

h => {                               // input = list h of opening hours
  for(                               //
    D = "montuewedthufrisatsun"      // D = list of abbreviated names of days
        .match(/.../g),              //
    d =                              // d = current day of week
    c =                              // c = current opening hours
    i =                              // i = first day of week to process
    j = 0;                           // j = day counter
    j < 8;                           // stop when 7 days have been processed
    y = d                            // update y = last day of current day range
  )                                  //
  h[i] == h[6] ?                     // while the opening hours of day #i equal the opening
    i++                              // hours of sunday: increment i
  : (v = h[d = (i + j++) % 7]) != c  // else, if the new opening hours (v) of the current
    && (                             // day (d) doesn't match the current opening hours (c):
      j > 1 &&                       //   if this is not the first iteration:
        console.log(                 //     print:
          D[x] +                     //     - the first day of the current day range (x)
          (x - y ?                   //     - followed by either an empty string
            '-' + D[y]               //       or a '-' and the last day of the range
          : ''),                     //       (if they differ)
          c                          //     - the corresponding opening hours
        ),                           //   (endif)
      x = d,                         //   update x = first day of current day range
      c = v                          //   update c = current opening hours
    )                                // (endif)
}                                    // (end)

Test cases

let f =

h=>{for(D="montuewedthufrisatsun".match(/.../g),d=c=i=j=0;j<8;y=d)h[i]==h[6]?i++:(v=h[d=(i+j++)%7])!=c&&(j>1&&console.log(D[x]+(x-y?'-'+D[y]:''),c),x=d,c=v)}

f(["0900-1800", "0900-1800", "0900-1800", "0900-1800", "0900-1800", "1100-1500", "1100-1500"]);
console.log('-');
f(["0900-1800", "0900-1800", "0900-1800", "0930-1700", "0900-1800", "1100-1500", "1100-1500"]);
console.log('-');
f(["1100-1500", "0900-1800", "0900-1800", "0900-1800", "0900-1800", "1100-1500", "1100-1500"]);
console.log('-');
f(["1100-1500", "1100-1500", "0900-1800", "0900-1800", "0900-1800", "0900-1800", "1100-1500"]);
console.log('-');
f(["1200-1500", "1100-1500", "0900-1800", "0900-1800", "0900-1800", "0900-1800", "1100-1500"]);


VSEPR Strikes Back! [Revamped Again] (Note: I know that the VSEPR method fails sometimes, and that there are exceptional molecules. The challenge is about the molecules which conform.)

Most people who have taken an introductory chemistry course know about molecules, and (probably) the VSEPR theory of chemical bonding. Basically, the theory predicts the shape of a molecule given three main properties:

A: The central atom. You may assume this is the first element appearing in the chemical formula; for example, in CH4, you may assume the central atom is C.
X: The number of atoms bonded to the central atom A.
E: The number of "lone electron pairs" on the central atom. For the purposes of this challenge, the number of outer electrons A has is given by the last digit of the element's column number on the periodic table.

If A is bonded to an element X in column 17 of the periodic table, there will be a mutual sharing of electrons, so that A effectively has one additional electron for each atom of X attached to it. (This does not apply for elements such as O or S in column 16.)

Each bond requires two of these electrons. Leftover electrons not used in bonding with other atoms are found in pairs of two, called lone pairs. So E is the number of electrons not used in bonding by the central atom A divided by 2. (It may be assumed that input will always lead to A having an even number of electrons.)

For example, a molecule which has 1 lone pair and 3 atoms bonded to the main atom is AX3E1, which is the trigonal pyramidal configuration. (There is always only 1 central atom, so A never has a subscript.)

The Challenge

Your job is, given a string representing a covalent chemical compound, to output the shape of that molecule. "But wait!", exclaim the exasperated programmers, "you can't expect us to input all of the molecular data for every element!" Of course we can, but as that wouldn't be fun, we'll only consider the compounds formed by the following 7 elements:

Carbon    C
Sulfur    S
Oxygen    O
Nitrogen  N
Chlorine  Cl
Bromine   Br
Fluorine  F

The input is any molecule composed of the above 7, such as CO2 or SF4, that is in the form AXN, where A and X are each one of the above seven element symbols, X is not C or N, and N is a number between 2 and 6 inclusive.

The output should be the name of the geometric shape of the molecule, for example "linear".

The following (don't get scared, I swear they're less than they seem!) is a list of all possible configurations along with their AXE number and a drawing of how they look (adapted from Wikipedia's nifty table):

Test Cases

  CO2: CO2 -> linear
  OF2: OF2 -> bent
  CCl2: CCl2 -> bent
  BrF3: BrF3 -> T-shaped
  SF4: SF4 -> seesaw

Notes:
 - We won't consider compounds in which the first element has a subscript other than 1, such as C2H4.
 - Standard loopholes apply.
 - This is a code golf, so the shortest answer wins (obviously)

Ruby, 250
s=gets
e=7-"FBOSN C".index(s[0])/2+(s[1]==?l?3:0)
x=s.reverse!.to_i
e+="Frl".index(s[2])?x:0
t="trigonal "
puts [["linear",b="bent",b],[t+"planar",t+p="pyramidal","T-shaped"],["tetr"+h="ahedral","seesaw"],[t+"bi"+p,"square "+p],["oct"+h]][x-2][e/2-x]

Note that with the rules as they are, AX2E3 and AX4E2 are not possible with the given elements, so they are not supported. All test cases passed.
with comments
s=gets                                     #get input with newline attached
e=7-"FBOSN C".index(s[0])/2+(s[1]==?l?3:0) #calculate the number of electrons (not lone pairs) from A. Note the addition required to differentiate C and Cl.
x=s.reverse!.to_i                          #reverse the input string so the number is at the beginning (after the newline) and evaluate the string as a number to get X.
e+="Frl".index(s[2])?x:0                   #if the character after the number is in "Frl" we have a halogen so increment number of electrons accordingly.
t="trigonal "                              #as "trigonal " goes at the beginning of the string, we cannot define it on the fly, it is defined as a constant here.
                                           #array of outputs below. note the subscripts at the end: x-2 to put it in the range 0..4 and e/2-x to convert e into the actual number of lone pairs.
puts [["linear",b="bent",b],[t+"planar",t+p="pyramidal","T-shaped"],["tetr"+h="ahedral","seesaw"],[t+"bi"+p,"square "+p],["oct"+h]][x-2][e/2-x]


Determine whether rational coordinates are in the right Sierpinski triangle The Sierpinski triangle is a set of points on the plane which is constructed by starting with a single triangle and repeatedly splitting all triangles into four congruent triangles and removing the centre triangle.  The right Sierpinski triangle has corners at (0,0), (0,1) and (1,0), and looks like this:

Some equivalent definitions of this set are as follows:

Points in the nth iteration of the process described above, for all n.
Points (x,y) with 0 <= x <= 1 and 0 <= y <= 1 such that for all positive integers n, the nth bit in the binary expansion of x and y are not both 1.
Let T = {(0,0),(1,0),(0,1)}

Let f be a function on sets of 2D points defined by the following:

f(X) = {(0,0)} ∪ {(x+t)/2 | x∈X, t∈T}

Then the right Sierpinski triangle is the topological closure of the least fixed point (by set containment) of f.
Let S be the square {(x,y) | 0<=x<=1 and 0<=y<=1}

Let g(X) = S ∩ {(x+t)/2 | x∈(X), t∈T} (where T is as defined above)

Then the right Sierpinski triangle is the greatest fixed point of g.

Challenge

Write a program or function which accepts 4 integers, a,b,c,d and gives a truthy value if (a/b,c/d) belongs to the right Sierpinski triangle, and otherwise gives a falsey value.

Scoring

This is a code golf.  Shortest code in bytes wins.

Test cases

The following are in the right Sierpinski triangle:

0 1 0 1
0 1 12345 123456
27 100 73 100
1 7 2 7
8 9 2 21
8 15 20 63
-1 -7 2 7

The following are not in the right Sierpinski triangle:

1 1 1 1
-1 100 1 3
1 3 1 3
1 23 1 7
4 63 3 66
58 217 4351 7577
-1 -7 3 7

Python 2, 68

lambda n,d,N,D:1>=n/d>=0<=N/D<=1and(n<<abs(D*d))/d&(N<<abs(D*d))/D<1

A nice way to check for gasket membership made ugly. If we were guaranteed that the inputs are non-negative and in the unit square, we would have 38:

lambda n,d,N,D:(n<<D*d)/d&(N<<D*d)/D<1

The idea is that we check whether a point lies within the gasket by checking whether their binary fraction expansions bitwise-AND to 0. To get the first k character of the expansion, we bit-shift the numerator k bits left before integer-dividing by the denominator. We need to make k sufficiently large to catch a repeat. We note that the binary expansion n/d has period at most d, so the joint expansions have period at most d*D, so k=d*D suffices.

The rest is to check whether the fraction is in the box and insulate against inputs given like -1/-3.


Time to settle this: Java vs C++ Story
In an unnamed company, some people use Java and some use C++. This was always a nuisance, and they kept on arguing which single language they should all be using. To settle the dispute, the management decided that they'll buy a translator program that will be able to rewrite their C++ programs to Java and vice versa. An important part of the translator will be a routine that will rewrite all the identifiers. This is because Java coders in the company write multiword identifiers in a different way than C++ coders in the company do. We will now describe both methods. In Java a multiword identifier is constructed in the following manner: the first word is written starting with a lowercase letter, and the following ones are written starting with an uppercase letter, no separators are used. All other letters are lowercase. Examples of Java identifiers are javaIdentifier, longAndMnemonicIdentifier, name and kSP.In C++ people use only lowercase letters in their identifiers. To separate words they use the underscore character '_'. Examples of C++ identifiers are cpp_identifier, long_and_mnemonic_identifier, name (here Java and C++ people agree), and k_s_p.
Task
Write the identifier translation routine/function/etc. Given an identifier, detect whether it is a Java identifier or C++ identifier (as defined below) and translate it to the other dialect. Translation must preserve the order of words and must only change the case of letters and/or add/remove underscores. You may assume all input to be valid, as checking was done for you in the superroutine.
More formally
A Java identifier only contains characters from [a-zA-Z] and starts with a lowercase letter. Every uppercase character is a word boundary.
A C++ identifier only contains characters from [a-z_] and additionally doesn't start or end with an underscore nor does it contain two adjacent underscores anywhere within. Every underscore is a word boundary.
Translation: switch every word boundary, that is, if it was an underscore, remove it and capitalize the following letter, if it was uppercase, prepend an underscore and lowercase the letter.
Input
The input consists of one line that contains an identifier. It consists of letters of the English alphabet and underscores. Other standard input styles are also valid.
Output
If the input identifier is a Java identifier, output/return its C++ version. If it is a C++ identifier, output/return its Java version. You may assume it will be at least one of those (both is possible).
Examples
long_boring_identifier  |  longBoringIdentifier
otherWay                |  other_way
same                    |  same
getHTTP                 |  get_h_t_t_p
invalid_Input           |  <undefined>

All the standard rules apply, none of the standard loopholes are allowed.

QuadR, 19 bytes

_(.)
[A-Z]
\u1
_\l&

Try it online!


Spherical excess of a triangle Spherical excess of a triangle
As we all know, the sum of angles of any planar triangle is equal to 180 degrees.
However, for a spherical triangle, the sum of angles is always greater than 180 degrees. The difference between the sum of the spherical triangle angles and 180 degrees is called spherical excess . The task is to compute the spherical excess of a triangle with given vertex coordinates.
Some background
A spherical triangle is a part of the sphere defined by three great circles of the sphere.
Both sides and angles of spherical triangle are measured in the term of angle measure, because each side can be considered as a intersection of the sphere and some planar angle with vertex at the center of the sphere:

Each three distinct  great circles define 8 triangles, but we only take proper triangles into consideration, ie. triangles whose angle and side measures satisfy

It's convenient to define vertices of a triangle in terms of geographic coordinate system. To compute the length of an arc of sphere given the longitude λ and latitude Φ of its ends we can use formula:

, where

or more explicitely:

(source: https://en.wikipedia.org/wiki/Haversine_formula)
The two basic formulas that can be used to solve a spherical triangle are:

the law of cosines:

the law of sines:

(source: https://en.wikipedia.org/wiki/Spherical_trigonometry#Cosine_rules_and_sine_rules)
Given three sides, it's easy to compute the angles using the cosine rule:

Finally, the spherical excess of a triangle is defined:

What's interesting about the relation between the spherical excess of a triangle and its area:

So on a unit sphere, the excess of a triangle is equal to area of that triangle!
The task
Write a function or a program that will compute spherical excess of a triangle in degrees given the triangle vertices coordinates.
The vertex coordinates are provided in terms of geographic coordinate system.
Each vertex should be passed in form [latitude in degrees][N|S][longitude in degrees][E|W]. Longitude and E or W can be skipped when latitude is 90 ie. 90N, 90S, 10N100E, 30S20W are proper vertex descriptions, while 80N or 55S are not.
The latitudes and longitudes are always integer in the test cases.
The answers with error less than one degree will be accepted (as in examples below). The result can be rendered as both real or integer therefore, up to your convenience.
Examples
Input
90N0E
0N0E
0N90E

Output
89.999989

Input
90N
0N0E
0N90E

Output
89.999989

Input
0N0E
0N179E
90N0E

Output
178.998863

Input
10N10E
70N20W
70N40E

Output
11.969793

In all test cases longitude and latitude are integer numbers.
Parsing the vertex coordinates is the part of the task, so a vertex must be passed as single string/literal , it's not allowed to pass 80N20E as four parameters/strings: 80, N, 20, E.
This is guaranteed that vertices are all distinct and neither two of the three vertices make an antipodal points pair.
Scoring
This is code-golf, so the shortest code wins.

Matlab, 288 266 bytes
Here the commented version that should explain what is going on:
                                  %parsing the input
for k=1:3;
    s=input('','s');              %request input
    if sum(s>57)<2;               %if we have only one letter, add arbitrary second coordinate
        s=[s,'0E'];
    end;
    S=1-2*(s(s>57)>80);           %calculate the sign of the coordinates
    s(s>57)=44;                   %replace letters with comma
    L(k,:)=eval(['[',s,']']).*S;  %evaluates string as list and multiply with signs
end;
i=[2,3,1];
                                  %calculate the angular distance between each pair of points
a=arrayfun(@distance,L(:,1),L(:,2),L(i,1),L(i,2))*pi/180;
                                  %evaluate the spherical excess
f=@(a,b,c)sum(acos((cos(a)-cos(b).*cos(c))./(sin(b).*sin(c))))-pi;
disp(f(a,a(i),a([3,1,2]))*180/pi)

Fully golfed (linebreaks can be removed):
for k=1:3;s=input('','s');if sum(s>57)<2;s=[s,'0E'];end;
s(s>57)=44;L(k,:)=eval([91,s,93]).*(1-2*(s(s<48)>80));end;
i=[2,3,1];p=pi/180;a=arrayfun(@distance,L(:,1),L(:,2),L(i,1),L(i,2))*p;
b=a(i);disp((sum(acos((cos(a([3,1,2]))-cos(b).*cos(a))./(sin(b).*sin(a))))-pi)/p)


xkcd challenge: "Percentage of the screen that is [x] color" So I think we've all probably seen this xkcd comic:

:

This might either be too general or too difficult, I'm not sure. But the challenge is to create a program in any language that creates a window that has at least 2 colors and displays in English words what percentage of the screen is each color.

ex. The simplest solution would be a white background with black letters that read "Percentage of this image that is black: [x]%. Percentage of this image that is white: [y]%"

You can go as crazy or as simple as you want; plain text is a valid solution but if you make interesting images like in the xkcd comic that's even better! The winner will be the most fun and creative solution that gets the most votes. So go forth and make something fun and worthy of xkcd! :)

So, what do you think? Sound like a fun challenge? :)

Please include a screenshot of your program running in your answer :)

JavaScript with HTML

I tried to reproduce the original comic more precisely. A screenshot is taken using the html2canvas library. The numbers are calculated repeatedly, so you can resize the window or even add something to page in real time.

Try it online: http://copy.sh/xkcd-688.html

Here's a screenshot:

Fraction of
this website
which is white _/
<canvas width=150 id=g></canvas>
&nbsp; Fraction of
- this website
&nbsp; which is black

0
<canvas style="border-width: 0 0 1px 1px; border-style: solid" id=z></canvas>

Location of coloured pixels in this website


Square Root Distance from Integers Given a decimal number k, find the smallest integer n such that the square root of n is within k of an integer. However, the distance should be nonzero - n cannot be a perfect square.

Given k, a decimal number or a fraction (whichever is easier for you), such that 0 < k < 1, output the smallest positive integer n such that the difference between the square root of n and the closest integer to the square root of n is less than or equal to k but nonzero.

If i is the closest integer to the square root of n, you are looking for the first n where 0 < |i - sqrt(n)| <= k.

Rules

You cannot use a language's insufficient implementation of non-integer numbers to trivialize the problem.
Otherwise, you can assume that k will not cause problems with, for example, floating point rounding.

Test Cases

.9         > 2
.5         > 2
.4         > 3
.3         > 3
.25        > 5
.2         > 8
.1         > 26
.05        > 101
.03        > 288
.01        > 2501
.005       > 10001
.003       > 27888
.001       > 250001
.0005      > 1000001
.0003      > 2778888
.0001      > 25000001
.0314159   > 255
.00314159  > 25599
.000314159 > 2534463

Comma separated test case inputs:

0.9, 0.5, 0.4, 0.3, 0.25, 0.2, 0.1, 0.05, 0.03, 0.01, 0.005, 0.003, 0.001, 0.0005, 0.0003, 0.0001, 0.0314159, 0.00314159, 0.000314159

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

Wolfram Language (Mathematica), 34 bytes

Min[⌈.5/#+{-#,#}/2⌉^2+{1,-1}]&

Try it online!

Explanation

The result must be of the form \$m^2 \pm 1\$ for some \$m \in \mathbb{N}\$. Solving the inequations \$\sqrt{m^2+1} - m \le k\$ and \$m - \sqrt{m^2-1} \le k\$, we get \$m \ge \frac{1-k^2}{2k}\$ and \$m \ge \frac{1+k^2}{2k}\$ respectively. So the result is \$\operatorname{min}\left({\left\lceil \frac{1-k^2}{2k} \right\rceil}^2+1, {\left\lceil \frac{1+k^2}{2k} \right\rceil}^2-1\right)\$.


Shortest code that throws SIGBUS We've had challenges for SIGSEGV and SIGILL so why not...

Write the shortest code that results in a Bus Error (SIGBUS) in any programming language.

Your program can't call raise() or kill(getpid(),sig) or pthread_kill(pthread_self(),sig), or any other equivalent.

x86_64 bytecode, 15 bytes

   0:   c7 04 24 00 00 04 00    movl   $0x40000,(%rsp)
   7:   9d                      popfq
   8:   8b 04 25 01 00 00 00    mov    0x1,%eax

Turns on the misaligned address trap flag and then immediately triggers it.


Code Golf: Leibniz Series This is the same question as Solve the CodeSprint4 Leibniz code golf challenge in Python in 66 characters. The variation is that I'm a C programmer. My code for the above question is:

#include <math.h>
main(){
int i,t,p;
scanf("%d",&t);
while(t--)
{
double s=1;
scanf("%d",&p);
for(i=1;i<p;++i)
s+=pow(-1,i)/(2*i+1);
printf("%.12lf\n",s);
}
}

Now I just need to know the places where I could reduce my code length.

Do everything in one line.
Don't read number of test cases, scanf will return -1 on EOF
Don't include anything, pow(-1,i) can be replaced by 1-i%2*2
Do the sum loop in reverse to save a variable.

Here is my 102 bytes code

main(n){gets(&n);for(double s;s=scanf("%d",&n)>0;printf("%.15f\n",s))while(--n)s+=(1-n%2*2)/(1.+2*n);}


I like to move it move it King Julian needs to get through the jungle, but he's feeling lazy. He wants a computer to be able to calculate a route through the jungle for him.

Using STDIN get a map of the jungle for the computer to crack. It will follow the following format:

01001E
010110
000P00
1100J1
S00111

The way the jungle map works is:

0 is ground that Julian can move along.

1 is dense impassable jungle.

P is an area with predators in it, that you must avoid at all costs.

J is relatively thick jungle. Julian's minions can break through one of these before tiring.

S is where Julian starts. It can be anywhere on the map.

E is where Julian wants to go; the end of the path. It also can be anywhere on the map, just like any other tile.

Every character is a tile on the map. Line breaks indicate a new row of tiles. If STDIN in your language does not support line breaks, the line break must be replaced by a space to signify a new row.

To move between the tiles, you must output a string using STDOUT containing the following special characters:

F - Forward

B - Backward

L - Rotate Julian left (90 degrees anticlockwise)

R - Rotate Julian right (90 degrees clockwise)

M - Minions destroy a J tile 1 tile forward from Julian, if there is one (M just clears out the tile, you still have to move onto it)

A possible output would be:

RFFLFRFMFLFRFLFF

Which solves the map above.

Notes:

If your program outputs a solution which hits predators, game over.
If you hit impassable jungle, you just bounce back to where you were before you ran into dense jungle, facing the same way. (Toward the jungle)
Julian starts facing upwards. (^ That way ^)
The output doesn't have to be the fastest solution, FFF and FBFBFBFBFBFFF are the same. However, outputting the fastest possible solution gives a -10% byte count bonus.
If a map is invalid, STDOUT 'Invalid map.' (That includes if the map is unsolvable)
A map cannot have rows or columns of different lengths; that makes it invalid.

Your answer should somewhat follow this format:

#Language name, *n* bytes

    code

Explanation (optional)

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

Groovy, 656 bytes

That was too long...

i={println"Invalid map."
System.exit(1)}
m=[]
q=System.in.newReader()
r=q.readLine()
while(r!=''){m<<r
r=q.readLine()}
o=m[0].size()
m.each{if(it.size()!=o)i()}
f=[0]*4
m.eachWithIndex{l,n->s=l.indexOf('S')
e=l.indexOf('E')
if(s!=-1){f[0]=s;f[1]=n}
if(e!=-1){f[2]=e;f[3]=n}}
v=[]
t={x,y,d->if(d.contains([x,y])|y>=m.size()|x>=o|x<0|y<0)return
a=m[y][x]
def p=d+[[x,y]]
if(a=='E')v=p
if(a=='J'|a=='0'|a=='S'){t(x-1,y,p)
t(x+1,y,p)
t(x,y+1,p)
t(x,y-1,p)}}
t(f[0],f[1],[])
if(!v)i()
o=0
p=''
v.inject{t,s->
c=m[s[1]][s[0]]
k=[t[0]-s[0],t[1]-s[1]]
z=[[0,1]:0,[1,0]:1,[0,-1]:2,[-1,0]:3][k]
p+=((((o-z)==0)?'':(z>0?'R':'L'))+(c=='J'?'M':'')+'F')
o=z
s}
println p

Output for the maze:

RFFLFRFMFLFRFLFF

Ungolfed:

invalid = {
    println "Invalid map."
    System.exit(1)
}
map = """01001E
010110
000P00
1110J1
S00111""".split('\n')

//map = [""]// TODO remove this, this is type checking only
//map.remove(0)
//reader = System.in.newReader()
//line = reader.readLine()
//while (line != '') {
//    map << line.replace('P','1')
//    line = reader.readLine()
//}

size = map[0].size()
map.each {if(it.size() != size) invalid()}

startAndEnd = [0,0,0,0]
map.eachWithIndex {it, idx -> s=it.indexOf('S');e=it.indexOf('E');
    if(s!=-1){ startAndEnd[0]=s; startAndEnd[1]=idx}
    if(e!=-1){ startAndEnd[2]=e; startAndEnd[3]=idx}}

def validPath = []

testMove = {x, y, visited ->// visited is an array of x y pairs that we have already visited in this tree
    if (visited.contains([x,y]) || y>=map.size() || x>=size || x<0 || y<0)
        return;

    def valueAtPos = map[y][x]
    def newPath = visited + [[x,y]]

    if (valueAtPos == 'E') validPath = newPath
    if ((valueAtPos == 'J' || valueAtPos == '0' || valueAtPos == 'S') && !validPath) {
        testMove(x-1, y, newPath)
        testMove(x+1, y, newPath)
        testMove(x, y+1, newPath)
        testMove(x, y-1, newPath)
    }
}
if (!validPath) invalid()
testMove(startAndEnd[0],startAndEnd[1], [])

println validPath

orintation = 0
path = ''
validPath.inject {first, second ->
    def chr = map[second[1]][second[0]]
    def sub = [first[0]-second[0],first[1]-second[1]]
    println "acc:$first, second:$second"
    def newOrin = [[0,1]:0, [1,0]:1, [0,-1]:2, [-1,0]:3][sub]
    path += ((((orintation - newOrin)==0)?'':(newOrin>0?'R':'L')) + (chr=='J'?'M':'') + 'F')
    orintation = newOrin
    second
}
println "path: $path"

I will try this again in python soon to see if I can shorten it further.


Generate random PESEL number From Wikipedia:

  PESEL is the
  national identification number used in Poland since 1979. It always
  has 11 digits, identifies just one person and cannot be changed to
  another one.

  It has the form of YYMMDDZZZXQ, where YYMMDD is the date of birth
  (with century encoded in month field), ZZZ is the personal
  identification number, X denotes sex (even number for females, odd
  number for males) and Q is a control digit, which is used to verify
  whether a given PESEL is correct or not.

  Having a PESEL in the form of ABCDEF GHIJK, one can check the
  vailidity of the number by computing the following expression:

  A*1 + B*3 + C*7 + D*9 + E*1 + F*3 + G*7 + H*9 + I*1 + J*3

  Then the last digit of the result should be subtracted from 10. If the
  result of the last operation is not equal to the last digit of a given
  PESEL, the PESEL is incorrect. This system works reliably well for
  catching one-digit mistakes and digit swaps.

Provide a short program to generate random, valid PESEL number:

It has to be a PESEL a person born in either 20th or 21st century
The birth birth date has to be random but doesn't have to validate leap years or number of days in a month (i.e. the numbers representing the day number have to be between 01 and 31)
All valid PESELs in this date range (01.01.1990-31.12.2099) must be possible
The shortest code (i.e. complete program code), in bytes, wins.

Perl, 162 bytes

@a=map{$==rand 10}0..9;$"='';$a[5]%=2if($a[4]%=4)==3;"@a[4,5]"||$a[5]++;$a[3]=($a[2]%=4)%2?$a[3]%3:1+$a[3]%9;$f=9;for(@a){$x+=$f*$_;$f-=$f%10==7?4:2}print@a,$x%10

Ungolfed:

# Array with random digits
# ------------------------
@a = map { $= = rand 10} 0..9;
# do not insert a space, if arrays are interpolated into strings
$" = ''; #"

# Day correction
# --------------
# The day must be in the range of "01" to "31":
# * map first digit to "0" to "3": $a[4] %= 4
# * map second digit to "0" to "1" if first digit is "3"
$a[5] %= 2 if ($a[4] %= 4 ) == 3;
# * set day to "01" if day is "00"
"@a[4,5]" || $a[5]++;

# Month correction
# ----------------
# The month must be in the range "01" to "12" or "21" to "32"
# to get a valid month and century:
# * map the month to "00" to "39"
# * if the first digit is odd (catching both centuries at once)
#   * then map the second digit to "0" to "2"      (for months: 10..12)
#   * otherwise map the second digit to "1" to "9" (for months: 01-09)
$a[3] = ($a[2] %= 4) % 2 ? $a[3] % 3: 1 + $a[3] % 9;

# Calculate the control digit
# ---------------------------
# Because of the modulo 10 operations, the formula for the calculation
# of the control digit is rewritten from
# Q = (10 - ((A + 3B + 7C + 9D + E + 3F + 7G + 9H + I + J) % 10)) % 10
# to
# Q = (9A + 7B + 3C + D - E - 3F -7G - 9H - 11I - 11J) % 10
$f = 9;
for (@a) {
    $x += $f * $_;
    $f -= $f % 10 == 7 ? 4 : 2
}

# Print the result and control digit
print @a, $x % 10

# TEST section
# ------------

;$Q = $x % 10; # remember control digit in $Q

# Pretty print PESEL
print "\n\n",
  "YY MM DD ZZZ X Q\n",
  "@a[0,1] @a[2,3] @a[4,5] @a[6,7,8] $a[9] $Q\n";
print "\n";

# Pretty print the date
$month = "@a[2,3]";
$century = "??";
$century = "19" if $month >= 1 and $month <= 12;
$century = "20" if $month >= 21 and $month <= 32;
printf "Date: $century@a[0,1]-%02d-@a[4,5]\n", $month % 20;
print "\n";

# Pretty print the gender
print "Gender: ", $a[9] % 2 ? "male" : "female", "\n";
print "\n";

# Calculate the control date the official way
print "Control digit:\n";
$sum = 0;
$f = 0;
for (my ($i, $f) = (0, 1); $i<10; $i++, $f+=2) {
    $f %= 10;
    $f += 2 if $f == 5;
    printf "  $a[$i] * $f = %2d\n", $a[$i] * $f;
    $sum += $a[$i] * $f;
}
print "  ", "-" x 10, "\n";
printf "  %10d\n", $sum;
printf "  $Q = (10 - ($sum % 10)) % 10 = %d\n", (10 - ($sum % 10)) % 10;

Examples

83102570819

YY MM DD ZZZ X Q
83 10 25 708 1 9

Date: 1983-10-25

Gender: male

Control digit:
  8 * 1 =  8
  3 * 3 =  9
  1 * 7 =  7
  0 * 9 =  0
  2 * 1 =  2
  5 * 3 = 15
  7 * 7 = 49
  0 * 9 =  0
  8 * 1 =  8
  1 * 3 =  3
  ----------
         101
  9 = (10 - (101 % 10)) % 10 = 9

20233143600

YY MM DD ZZZ X Q
20 23 31 436 0 0

Date: 2020-03-31

Gender: female

Control digit:
  2 * 1 =  2
  0 * 3 =  0
  2 * 7 = 14
  3 * 9 = 27
  3 * 1 =  3
  1 * 3 =  3
  4 * 7 = 28
  3 * 9 = 27
  6 * 1 =  6
  0 * 3 =  0
  ----------
         110
  0 = (10 - (110 % 10)) % 10 = 0


Custom Number Base Converter The powers that be want to be able to quickly convert any number they have into their own number base using any format they would like.

Input

Your program must accept 3 parameters.

Number: The string number to be converted
InputFormat: the base string the number is currently in
OutputFormat: the base string that the number is to be converted to.

Output

Your program must convert the Number from the old number base InputFormat to the new number base OutputFormat

Examples

("1","0123456789","9876543210") = "8"
("985724","9876543210","0123456789ABCDEF") = "37C3"
("FF","0123456789ABCDEF","0123456789") = "255"
("FF","0123456789ABCDEF","01234567") = "377"
("18457184548971248772157", "0123456789","Aa0Bb1Cc2Dd3Ee4Ff5Gg6Hh7Ii8Jj9Kk,Ll.Mm[Nn]Oo@Pp#Qq}Rr{Ss-Tt+Uu=Vv_Ww!Xx%Yy*Zz") = ",sekYFg_fdXb"

Additional

The new base 77 test is not required props if it works though

if your in a language where you have to convert to a number first and are locked within 32Bit you can skip it.
as it's an additional test.

All examples were generated by PHP 7.2 with the bcmath extension using the following code (vars mins but code formatted). there will probably be a shorter way this is just the way I came up with for the system I needed to do this with would be nice to see if anyone could come up with a shorter version though.

PHP 7.2 (bcmath - extension) 614 bytes

<?php
function f($a, $b, $c)
{
    $d= str_split($b,1);
    $e= str_split($c,1);
    $f= str_split($a,1);
    $g=strlen($b);
    $h=strlen($c);
    $k=strlen($a);
    $r='';
    if ($c== '0123456789')
    {
        $r=0;
        for ($i = 1;$i <= $k; $i++)
            $retval = bcadd($retval, bcmul(array_search($f[$i-1], $d),bcpow($g,$k-$i)));
        return $r;
    }
    if ($b!= '0123456789')
        $l=f($a, $b, '0123456789');
    else
        $l= $a;
    if ($l<strlen($c))
        return $e[$l];
    while($l!= '0')
    {
        $r= $e[bcmod($l,$h)].$r;
        $l= bcdiv($l,$h,0);
    }
    return $r;
}

Try it Online

Scoring

This is code golf; shortest code wins. Standard loopholes apply.

MATL, 2 bytes

Za

Try it online!
All test cases.

For the Za lord!


The easy way to code-golf ascii art! Task:

There are a lot of answers on this site that are arranged into ascii art, like this one. Usually the arrangement is done manually, but wouldn't a program help with that? :)

Your program will take 3 inputs:

The code, as one single line
The number of lines in the pattern (can be omitted if not necessary)
The pattern itself, as *s or another char

Rules:

You have to write a program (not a function) that reads from stdin
The text is placed left-to-right per line
If there is not enough text to fill the pattern, put .s in the remaining spaces
If there is too much text to fill the pattern, print it out after the output
code-golf, so the shortest code, in bytes wins

Sample Runs:
Input (Exact Fit test):
qwertyuiopasdfghjklzxcvbnm
4
***** * ***
*   * * *
*   * * *
***** * ***

Output:
qwert y uio
p   a s d
f   g h j
klzxc v bnm

Input (Extra characters test):
qwertyuiopasdfghjklzxcvbnm12345
4
***** * ***
*   * * *
*   * * *
***** * ***

Output:
qwert y uio
p   a s d
f   g h j
klzxc v bnm
12345

Input (Insufficient Characters test):
qwertyuiopasdfg
4
***** * ***
*   * * *
*   * * *
***** * ***

Output:
qwert y uio
p   a s d
f   g . .
..... . ...

Perl 6: 60 characters EDIT: 38 points (see bottom)

  #C#O     D#E#G#O       #L#
#F    #.#S#       T#A#C#K
  get\     .subst(       "*"
,{    shift       BEGIN [
  get\     .comb,\       "."
xx    * ]},       :g)\ .\
  say\     xx get\       ()\
#E    #X#C#       H#A#N#G
  #E#.     #C#O#M#       #!#

If you don't appreciate my terrible art skills, here's the golf:

get.subst("*",{shift BEGIN [get.comb,"."xx*]},:g).say xx get

This one does weird things with evaluation times.

First, the BEGIN keyword forces [get.comb, "." xx *] to be evaluated first, putting into an array the list of characters that make up "the code", followed by an infinite amount of "."s.

Next, the get at the end is evaluated, getting the number of lines of the ASCII art template. The xx operator repeats the first part of the program this many times. This makes more sense when you realize that code() xx count() is basically sugar for code() for 1..count(): count() should be evaluated first.

Finally, the get in the beginning of the program gets a line of the ASCII art template and substitutes every "*" with a value shifted off of the beginning of the array we made before everything else ({shift BEGIN …}).

EDIT:

Golfed down to 37 characters, plus one for the command line switch:

perl6 -pe's:g[\*]=shift BEGIN [get.comb,"."xx*]'

This is the same concept as the original, the -p switch iterating over each line (after the BEGIN has read in "the code"), and substituting all *s with the next letter from "the code" before printing it. The input format for this shouldn't include the number of lines of the format.


Remove all occurrences of the first letter of a string from the entire string Given an input string only containing the characters A-Z, a-z, and spaces, remove all occurrences of the uppercase and lowercase versions of the first character of the string (if the first character is A remove all As and as, if the first character is (space) remove all spaces), and print the output.

Example cases:

Testing Testing One Two Three -> esing esing One wo hree
Programming Puzzles and Code Golf -> rogramming uzzles and Code Golf
How much wood would a woodchuck chuck if a woodchuck could chuck wood -> ow muc wood would a woodcuck cuck if a woodcuck could cuck wood
{space}hello world -> helloworld
welcome to WATER WORLD -> elcome to ATER ORLD

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

Notes:

Input will always be 2 or more valid characters.
Output will never be an empty string.

brainfuck, 219 bytes

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

(Requires tape that either allows the pointer to go to the negatives or loops to the end if it tries. Also requires , to return 0 at EOF. In my experience, most interpreters meet these requirements by default.)

This actually turned out to be pretty easy! I wouldn't be surprised if it's golfable (I have some idea of where there might be wasted bytes but I'm not super sure if it'll pan out). Still, getting it work wasn't really a challenge at all.

This code treats everything with an ASCII value below 97 as an uppercase character. If the first character is space, it'll try to remove any occurrences of a "lowercase space" (i.e. chr(32+32), i.e. @) from the string. This is okay, because only letters and spaces will ever be present.

With comments:

to make comments shorter: everywhere it says "fc" means "first character"

#################################### GET FC ####################################

+[+[>+<+<]>]        shortest way to get 96
                    any number above 89 and less than 97 would work because this
                    is only for figuring out if the first character is capital

,[<+<+>>-]          create two copies of the first character

### current tape: | fc | fc | 000 | 096 | ###
###      pointer:              ^          ###

########################### FIND MAX(FC MINUS 96; 0) ###########################

>[                  96 times:

  <<                  go to the cell with the first char

  [->]                if not 0: sub one and move right

  ### current tape: | fc | char being worked on | 000 | 096 | ###
  ###      pointer:                           ^ OR ^          ###

  >[<]>               collapse the wavefunction; sync the branches

-]

### current tape: | fc | fc is lowercase ? nonzero : zero | 000 | 000 | ###
###      pointer:                                                  ^    ###

############################# GET BOTH CASES OF FC #############################

++++[<++++++++>-]   get 32 (add to uppercase character to get lowercase)

<<[                 if the character is already lowercase:

  [-]                 clear the lowercase flag

  ----[>-<----]>-     sub 64 from the cell with 32

<]

<[>+>+<<-]          add fc to the 32 or minus 32 to get both cases

### current tape: | 000 | fc | other case of fc | ###
###      pointer:    ^                            ###

###################### LOOP THROUGH REMAINING CHARACTERS #######################

<,[                 for each character:

  [>+>>>+>>+>+<<<<<<<-]
                      make four copies
                      (only 3 are strictly needed; 4th will resync a branch)

  >>                  go to the first case of fc

  [<<+>>-]<<[>->+<<-] subtract one case of fc from one copy

  >[[-]+<]            if the result is nonzero set it to 1

  >[>]<<              go to the other case of fc (and resync branches)

  [>>+<<-]>>[<-<+>>-] subtract other case of fc from other copy

  <[[-]+>]            if the result is nonzero set it to 1

  >>[<]               resync branches using extra copy

  <<<<[>>>+<<<-]>>>   add results together

  -                   subtract 1

   if the character exactly matched either case: 1 plus 0 minus 1 = 0
  if the character exactly matched neither case: 1 plus 1 minus 1 = 1
    if the character exactly matched both cases: impossible

  [                   if the result is 1:

    >>.<<               output character

    -                   set cell to 0 to kill loop

  ]

  >>>[[-]<]           clean up remaining copies

  <<<<<,              get next character; or end loop if done

]


Is this a valid input for this hardware? The (slightly harder, but still easy) sequel of Generate input for this hardware.

Background

I have a hardware that has a 32-bit input register. The register has the following characteristics:

The 32-bit register consists of eight 4-bit fields.
Each 4-bit field holds a value in signed-magnitude; it can hold an integer between -7 and +7 inclusive, including -0 and +0 (signed zeroes).

For example, the hexadecimal value 0xABCD1234 represents the field values [-2, -3, -4, -5, +1, +2, +3, +4]. In fact, one hex digit represents one 4-bit value with the following mapping:

Hex    |  Input value
---------------------
0 ~ 7  |  +0 ~ +7
8 ~ F  |  -0 ~ -7

In order to correctly operate this hardware, the 8 field values must be strictly increasing from left (most significant) to right (least significant). For signed zeros, -0 is considered to be less than +0.

The following are the examples of valid inputs:

field values for 8 fields        => 32-bit register value
[-7, -6, -5, -4, -3, -2, -1, -0] => 0xFEDCBA98
[+0, +1, +2, +3, +4, +5, +6, +7] => 0x01234567
[-7, -4, -3, -2, -0, +1, +3, +4] => 0xFCBA8134
[-2, -1, -0, +0, +3, +4, +5, +7] => 0xA9803457

The following are the examples of invalid ones:

field values for 8 fields        => 32-bit register value
[+7, +6, +5, +4, +3, +2, +1, +0] => 0x76543210 // not increasing
[-2, -1, -0, -0, +1, +2, +3, +4] => 0xA9881234 // not strictly increasing, due to duplicates
[-3, -2, -1, +0, -0, +1, +2, +3] => 0xBA908123 // +0 is greater than -0

Task

Given the register value, determine if it is a valid input to the hardware.

Input and output

The input (the register value) is an unsigned 32-bit integer. You can take it as an integer, a string, or a list of digits. A string or list of digits can be in base 2, 8, 10 or 16, least-significant-digit-first or most-significant-digit-first, with or without leading zeros or base prefixes.

For example, if an input value is 0x01234567, possible representations in base 16 include "0x01234567", "01234567", "1234567", "76543210" (reversed order of digits), [0, 1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1, 0].

The output is a boolean, indicating whether the given input is valid or not. You can choose to output either:

Any of the truthy/falsy values as defined by the language of your choice

The actual result values may differ between inputs (e.g. output 1 for a truthy input and 2 for another truthy one).
Swapping truthy and falsy values is not allowed.

Any two distinct constant values for true/false respectively

In this case, the result values should exactly be one of the two constant values.

Scoring

The standard code-golf rules apply. The shortest code in bytes wins.

Test cases

Expected output: Valid

0xFEDCBA98
0xEDCBA980
0x80123456
0x01234567
0xFCB98037
0xEDB12345

Expected output: Invalid

0x76543210
0x1A2B3C4D
0x12345678
0xBA988123
0xBA908123
0x00123456
0xB9882347
0xDC914556

Python 2, 52 bytes

lambda s:eval("'EDCBA9801234567'.find(%r)<"*8%s+'s')

Try it online!

Takes input as a tuple like ('F', 'E', 'D', 'C', 'B', 'A', '9', '8').

The idea is to produce out and evaluate a long chain of inequalities like:

'EDCBA9801234567'.find('F')<'EDCBA9801234567'.find('E')<'EDCBA9801234567'.find('D')<'EDCBA9801234567'.find('C')<'EDCBA9801234567'.find('B')<'EDCBA9801234567'.find('A')<'EDCBA9801234567'.find('9')<'EDCBA9801234567'.find('8')<s

The s at the end of the chain takes care of the extra trailing < symbol by giving an always-true comparison of "number < string" in Python 2 logic.


Random Sentence Generator Write the shortest program you can in any language that reads a context-free grammar from and the number of sentences to produce from stdin, and generates that many random sentences from the grammar.

Input

Input will come in the following format:

n <START>
{"<A>":["as<A>df","0<A>","<B><C>","A<A>", ...], "<B>":["1<C>1","\<<T>>",...], ...}

n is the number of sentences to generate.  <START> is identifier of the starting nonterminal symbol.

The grammar is enclosed in the {} and is formatted as follows:

Rules are of the form "<S>":[productions].  <S> is the identifier of the nonterminal.

Rules are delimited with commas.
The right-hand side of a rule is a double-quoted string whose first and last characters are "<" and ">", respectively. The remaining character should be in [A-Z] (upper-case alpha).

productions is a comma-delimited list of double-quoted strings, representing productions.  All characters, including whitespace, in the rule are terminal symbols, except those that are enclosed in angle brackets ("<" and ">"), which are non-terminal symbols and will be the left-hand side of another rule.  An open angle bracket may be escaped, but there is no need to escape a close angle bracket.

Productions will not contain newlines or the newline escape sequence.

Output

You should print each generated sentence to stdout with a trailing newline.

Test Cases
5 sets of balanced parentheses:

5 <S>
{"<S>":["<S><S>", "(<S>)", ""]}

Example result:

(())()
()
()()()

(())(()())((((()))()()))

4 postfix arithmetic expressions (note whitespace within strings is significant, whitespace elsewhere is not):

4 <S>
{"<S>":["<N>", "<S> <S> <O>"], "<O>":["+","-","*","/"], "<N>":["<D><N>", "<D>"],
 "<D>":["1","2","3","4","5","6","7","8","9","0"]}

Example result:

1535235 76451 +
973812
312 734 99 3 + / *
1 1 1 1 1 + - * +

I felt like doing a little JavaScript.
Also, I cried a little on the inside when I wrote "document.write"

    <textarea id='ta' cols='80'></textarea>
    <button onclick="foo()">go</button>

Input:

10
{"":["ab","cd",""],"":["e<C>e"],"<C>":["z","",""]}

Output:

ccaaceeeeezeeeeedbbdd
accccceeeezeeeedddddb
aecezedeb
eaezebe
ccccaacezedbbdddd
eeeaaaceecacezedbdeedbbbeee
acaecaeaaeacccceeeeeeeaeeezeeebeeeeeeeddddbebbebdebdb
aaceezeedbb
aacezedbb
ceeaceecacaacezedbbdbdeedbeed


Make a working digital clock with ascii numbers The challenge is make a digital clock that exhibits ascii numbers in a 24-hour format like:

 _   _     _   _
|_| |_| . |_| |_|
|_| |_| . |_| |_|

or

 _   _         _
 _|  _| . |_| |_
|_   _| .   |  _|

and updates the screen every 1 minute (or every 1 second, for praticity reasons). It must reset to 00:00 after 23:59.

Python, 411 408 chars

import time,os
s=" ";p=".";a=s*3;b=" _ ";c="|_|";d="| |";e="|  ";f="  |";g="|_ ";h=" _|";P=[s,p,p]
z=[[b,d,c],[a,f,f],[b,h,g],[b,h,h],[a,c,f],[b,g,h],[b,g,c],[b,f,f],[b,c,c],[b,c,h]]
A=range(10);B=A[:6];C=A[:3]
while 1:
 for i in C:
  for j in A:
   if i==2&(j==4):break
   for k in B:
    for l in A:
     for m in C:
      print z[i][m]+s+z[j][m]+P[m]+z[k][m]+z[l][m]
     time.sleep(1);os.system('clear')

Not so pretty but working.


Help me cheat at Cheat Cheat is a card game where you're trying to get rid of your hand. A turn looks something roughly like this:

Determine what card rank you have to play that turn. In most variants this is one rank higher than the previous turn.
Play 1-4 cards, face down. These don't have to match the valid rank. If they don't, it's considered a cheat. At this point any player may challenge you.

If nobody challenges you, play continues to the next player.
If somebody challenges you and you didn't cheat, they have to take all of the played cards.
If somebody challenges you and you did cheat, you have to take all of the played cards.

The strategy is mostly a mix of bluffing and card counting. I'm bad at math, though, so I'm going to cheat at Cheat and bring a bot with me.

Input

The input will be, in any order or format you want:

The player's hand. If I know that they must have cards (for example, I've seen them pick them up), those will be listed in ascending order. Any unknowns will be listed afterwards as ?. For example, if they have six cards and I know that two are 1's and one is a 4, a valid representation of the hand is 114???. ?'s will always be listed after known cards. 141??? and 11???4 are both invalid inputs and your code doesn't need to handle them.
The cards I definitely know are not part of their hand (I have them, I saw someone else pick them up, etc). The list will be in ascending order of rank. The list may be empty.
The cards the player claimed to play. If they claimed to play 3 7's, a possible input here would be 777. The cards will always be the same rank.

The number of played cards will always be 1-4 and the ranks will always be 0-9. A rank will never appear more than four times in their hand + not their hand.

This is an example valid input:

33577??
01555688
55

This is an example invalid input:

35377?? # Out of order
7779    # Five 7's in total
23      # Two separate ranks played

Output

A truthy value if we should definitely challenge. A falsey value if we might not want to challenge.

We always challenge if we know they cheated. We know they cheated if they played cards they couldn't possibly have:

12

3  # They don't have any 3's or ?'s
-------------
12?

33 # Fewer ?'s than played cards
-------------
123?
333
33 # Since we have three 3's they can't have two

The other time we challenge is if they play their last cards. Even if the play's legit it would end the game so we might as well challenge it.

1

1 # They'd win, so challenge anyway

More Test Cases

Truthy (should challenge)

11445678?

22
-------------
????????
4
4444
-------------
12345678

9

Falsey (should not challenge)

1?
222
2
-------------
12?
22
22
-------------
?????

1111

Scoring

Shortest code wins.

Pyth, 22 bytes
!}zS+*hzhS,/Q\?-4l@z+w

Try it online.


Toggle some bits and get a square Given an integer \$N>3\$, you have to find the minimum number of bits that need to be inverted in \$N\$ to turn it into a square number. You are only allowed to invert bits below the most significant one.

Examples

\$N=4\$ already is a square number (\$2^2\$), so the expected output is \$0\$.
\$N=24\$ can be turned into a square number by inverting 1 bit: \$11000 \rightarrow 1100\color{red}1\$ (\$25=5^2\$), so the expected output is \$1\$.
\$N=22\$ cannot be turned into a square number by inverting a single bit (the possible results being \$23\$, \$20\$, \$18\$ and \$30\$) but it can be done by inverting 2 bits: \$10110 \rightarrow 10\color{red}0\color{red}00\$ (\$16=4^2\$), so the expected output is \$2\$.

Rules

It is fine if your code is too slow or throws an error for the bigger test-cases, but it should at least support \$3 < N < 10000\$ in less than 1 minute.
This is code-golf!

Test cases

    Input | Output
----------+--------
        4 | 0
       22 | 2
       24 | 1
       30 | 3
       94 | 4
      831 | 5
      832 | 1
     1055 | 4
     6495 | 6
     9999 | 4
    40063 | 6
   247614 | 7        (smallest N for which the answer is 7)
  1049310 | 7        (clear them all!)
  7361278 | 8        (smallest N for which the answer is 8)
100048606 | 8        (a bigger "8")

Or in copy/paste friendly format:

[4,22,24,30,94,831,832,1055,6495,9999,40063,247614,1049310,7361278,100048606]

Ruby, 74 bytes

->n{(1..n).map{|x|a=(n^x*x).to_s 2;a.size>Math.log2(n)?n:a.count(?1)}.min}

Try it online!

This simply generates the sequence \$\left[1^2, 2^2, \ldots, n^2\right]\$ (which is far more than enough), XORs it with \$n\$, and then takes either the number of 1s in its binary representation if the number of bits is less than or equal to \$\log_2n\$, or \$n\$ otherwise. It then takes the minimum number of bits flipped. Returning \$n\$ instead of the number of bits flipped when the highest bit flipped is greater than \$\log_2n\$ prevents these cases from being chosen as the minimum, as \$n\$ will always be greater than the number of bits it has.

Thanks to Piccolo for saving a byte.


Play Best Card in Euchre Input:

Firstly
An array of three cards representing the cards played by each player formatted like

[JD][TH][9S]

Representing

Jack of Diamonds, 10 of Hearts, and Nine of Spades.

As you always sit across from your team-mate in Euchre, the second element represents your team mate's play. Here, the TH.

Secondly
A Single Char, String, etc representing the trump suit formatted like

S, D, C, H

representing

Spades, Diamonds, Clubs, Hearts

Thirdly
an array of four cards representing your hand formatted like

[KD][JC][QH][AS]

representing

King of Diamonds, Jack of Clubs, Queen of Hearts, Ace of Spades

Objective:

Given the three inputs, output the best possible card to add to the cards that have been played such that it meets the following criteria:

It takes the hand if it can, if not output the least valuable card
It takes the hand if it can, however it will not trump your team mate unless it is unavoidable
If it can take the hand, it does so by using the least valuable card. (If you have an ace and a queen that can win the hand, you play the queen).
Any plays must follow suit as required by the rules at the bottom.

Output format like [JD]

Formatting

A - Ace
K - King
Q - Queen
J - Jack
T - Ten
9 - Nine

H - Hearts
D - Diamonds
S - Spades
C - Clubs

TH, 9D, JD, QH, AD, 9C, TC

Examples

In: [QD][KD][9C], "C", [AH][JH][QH][9H]

Out: 9H

Reason: As clubs are trump, the 9C is winning the hand, we are unable to take the hand so we should discard our lowest card, here the 9H

In: [QD][KD][AD], "H", [AH][JH][QH][9H]

Out: 9H

Reason: As Hearts are trump, the Ace of Diamonds is currently winning the hand, we are able to trump the hand so we should use our lowest card, here the 9H

In: [QD][KD][TD], "D", [AD][JH][QH][9D]

Out: 9D

Reason: As diamonds are trump and we are currently winning the hand, we should play the 9D because our partner currently is winning the hand, so we want to play the 9D over the AD

In: [QH][KH][JH], "D", [AD][JD][QH][9D]

Out: QH

Reason: As Diamonds are trump our opponents are winning with the left Bower JH We have the right bower but cannot trump him because QH was led and we must follow suit, the QH

In: [QH][KH][JH], "D", [AD][JD][QC][9D]

Out: JD

Reason: As Diamonds are trump our opponents are winning with the left Bower JH We have the right bower and since we have no Diamonds we can trump over him with the JD

Euchre Card Strengths

If Hearts is trump:

JH
JD
AH
KH
QH
TH
9H

See the Euchre Rules if you are unfamiliar with the strength of different cards in Euchre

Since this is Code-Golf the shortest code wins!

Good Luck and have fun!

Perl - 557 532 511 490 482 384 363

($p,$t,$h)=@ARGV;%L=(H=>D,D=>H,C=>S,S=>C);$B=%L{$t};$_="\]$p$h\[";s/(.$t)/0$1/g;s/J$B/01$B/;s/0J/00/;s/J/R/g;s/9/Z/g;($T,@C)=split/\]\[/,$_;$s=$C[0];$s=~s/.+(.)/$1/;$s=~s/$t/0/;$X=(sort@C[0..2])[0];@M=@C[3..6];@F=(grep{/$s/}@M);@M=@F if@F;$w=(sort@M)[@M-1];push@M,$X;foreach$g(sort@M){$g ne$X?$b=$g:last}$_=$C[1]eq$X||!$b?$w:$b;s/.(..)/$1/;s/Z/9/;s/0|1|R/J/;print

How it works

Try it online!

First it reads args and finds the left-bauer's suit (jack of the same color as trump) with a hash lookup:

($p,$t,$h)=@ARGV;
%L=(H=>D,D=>H,C=>S,S=>C);
$B=%L{$t};

Then it combines all cards into one string and does some replacements, making the cards naturally sort in the correct order for euchre:

$_="\]$p$h\[";
s/(.$t)/0$1/g; # trump cards start with '0'
s/J$B/01$B/;   # left-bauer's 'J' changes to '01', making it trump
s/0J/00/;      # right-bauer's 'J' changes to '0'
s/J/R/g;       # all other jacks have 'J' changed to 'R'
s/9/Z/g;       # all 9s change to Z
($T,@C)=split/\]\[/,$_;

At the end of this block, the card string is then split on the brackets, which builds an array of all cards where:

index 0 = opponent's lead card
index 1 = teammate's card
index 2 = other opponent's card
indices 3-6 represent the hand

The lead suit is parsed from the first card, but the suit changes to '0' to represent trump if trump was led:

$s=$C[0];
$s=~s/.+(.)/$1/;
$s=~s/$t/0/;

The best card in-play is found by sorting the first three cards and retrieving the first card:

$X=(sort@C[0..2])[0];

The playable cards are found. If any cards in-hand match the lead suit, then only those cards remain. Otherwise all cards are considered playable:

@M=@C[3..6];
@F=(grep{/$s/}@M);
@M=@F if@F;

The 'throwaway' card is found by returning the last card in the sorted array of playable cards:

$w=(sort@M)[@M-1];

The lowest 'winning' card that can win the trick is found by adding the highest card in-play to the array of playable cards, sorting the array, and iterating over it until the highest card in-play is found. The 'winning' card is the card from the previous iteration:

push@M,$X;
foreach$g(sort@M){$g ne$X?$b=$g:last}

The correct play is then evaluated. The 'throwaway' card is chosen if any of the following are true:

The best card on the table has an index of 1 in the unsorted array of all cards, meaning it belongs to our teammate
The search for the lowest 'winning' card came up null, meaning our opponent's best card is higher than all cards in the hand

Otherwise the 'winning' card is returned:

$_=$C[1]eq$X||!$b?$w:$b;
s/.(..)/$1/; # remove the '0' that indicated trump
s/Z/9/;      # get those 9s back
s/0|1|R/J/;  # fix the jacks
print


Telephone number in spoken words Goal

Write a program or function that translates a numerical telephone number into text that makes it easy to say.  When digits are repeated, they should be read as "double n" or "triple n".

Requirements

Input

A string of digits.

Assume all characters are digits from 0 to 9.
Assume the string contains at least one character.

Output

Words, separated by spaces, of how these digits can be read out loud.

Translate digits to words:

0 "oh"
1 "one"
2 "two"
3 "three"
4 "four"
5 "five"
6 "six"
7 "seven"
8 "eight"
9 "nine"
When the same digit is repeated twice in a row, write "double number".
When the same digit is repeated thrice in a row, write "triple number".
When the same digit is repeated four or more times, write "double number" for the first two digits and evaluate the rest of the string.
There is exactly one space character between each word.  A single leading or trailing space is acceptable.
Output is not case sensitive.

Scoring

Source code with the least bytes.

Test Cases

input        output
-------------------
0123         oh one two three
4554554      four double five four double five four
000          triple oh
00000        double oh triple oh
66667888     double six double six seven triple eight
19999999179  one double nine double nine triple nine one seven nine

8088 Assembly, IBM PC DOS, 164 159 156 155 bytes
Binary:
00000000: d1ee 8a0c 03f1 53fd ac3a d075 0343 e2f7  ......S..:.u.C..
00000010: 85db 741c 5f8a d043 f6c3 0174 0a57 bd64  ..t._..C...t.W.d
00000020: 0155 83eb 0374 0957 bd5d 0155 4b4b 75f7  .U...t.W.].UKKu.
00000030: 8ad0 2c2f 7213 518a f0b0 24b1 31bf 6a01  ..,/r.Q...$.1.j.
00000040: fcf2 aefe ce75 fa59 57e2 bc5a 85d2 740c  .....u.YW..Z..t.
00000050: b409 cd21 b220 b402 cd21 ebef c364 6f75  ...!. ...!...dou
00000060: 626c 6524 7472 6970 6c65 246f 6824 6f6e  ble$triple$oh$on
00000070: 6524 7477 6f24 7468 7265 6524 666f 7572  e$two$three$four
00000080: 2466 6976 6524 7369 7824 7365 7665 6e24  $five$six$seven$
00000090: 6569 6768 7424 6e69 6e65 24              eight$nine$

Build and test executable using xxd -r from above, or download PHONE.COM.
Unassembled listing:
D1 EE       SHR  SI, 1              ; point SI to DOS PSP (80H) for input string
8A 0C       MOV  CL, BYTE PTR[SI]   ; load input string length into CX
03 F1       ADD  SI, CX             ; move SI to end of input
53          PUSH BX                 ; push a 0 to signal end of output stack
        CHAR_LOOP:
FD          STD                     ; set LODS direction to reverse
AC          LODSB                   ; load next char from [SI] into AL, advance SI
3A D0       CMP  DL, AL             ; is it same as previous char?
75 03       JNZ  NEW_CHAR           ; if not, it's a different char
43          INC  BX                 ; otherwise it's a run, so increment run length
E2 F7       LOOP CHAR_LOOP          ; move on to next char
        NEW_CHAR:
85 DB       TEST BX, BX             ; is there a run greater than 0?
74 1C       JZ   GET_WORD           ; if not, look up digit name
5F          POP  DI                 ; get name for the current digit
8A D0       MOV  DL, AL             ; save current char in DL
43          INC  BX                 ; adjust run count (BX=1 means run of 2, etc)
F6 C3 01    TEST BL, 1              ; is odd? if so, it's a triple
74 0A       JZ   IS_DBL             ; is even, so is a double
57          PUSH DI                 ; push number string ("one", etc) to stack
BD 0164     MOV  BP, OFFSET T       ; load "triple" string
55          PUSH BP                 ; push to stack
83 EB 03    SUB  BX, 3              ; decrement run count by 3
74 09       JZ   GET_WORD           ; if end of run, move to next input char
        IS_DBL:
57          PUSH DI                 ; push number string to stack
BD 015D     MOV  BP, OFFSET D       ; load "double" string
55          PUSH BP                 ; push to stack
4B          DEC  BX                 ; decrement by 2
4B          DEC  BX
75 F7       JNZ  IS_DBL             ; if not end of run, loop double again
        GET_WORD:
8A D0       MOV  DL, AL             ; save current char into DL
2C 2F       SUB  AL, '0'-1          ; convert ASCII char to 1-based index
72 13       JB   NOT_FOUND          ; if not a valid char, move to next
51          PUSH CX                 ; save outer loop counter
8A F0       MOV  DH, AL             ; DH is the index to find, use as scan loop counter
B0 24       MOV  AL, '$'            ; word string is $ delimited
B1 31       MOV  CL, 031H           ; search through length of word data (49 bytes)
BF 016A     MOV  DI, OFFSET W       ; reset word data pointer to beginning
FC          CLD                     ; set DF to scan forward for SCAS
        SCAN_LOOP:
F2/ AE      REPNZ SCASB             ; search until delimiter '$' is found in [DI]
FE CE       DEC  DH                 ; delimiter found, decrement counter
75 FA       JNZ  SCAN_LOOP          ; if counter reached 0, index has been found
59          POP  CX                 ; restore outer loop position
57          PUSH DI                 ; push string on stack
        NOT_FOUND:
E2 BC       LOOP CHAR_LOOP          ; move to next char in input
        OUTPUT_STACK:
5A          POP  DX                 ; get string from top of stack
85 D2       TEST DX, DX             ; it is the last?
74 0C       JZ   EXIT               ; if so, exit
B4 09       MOV  AH, 09H            ; DOS display string function
CD 21       INT  21H                ; write string to console
B2 20       MOV  DL, ' '            ; load space delimiter
B4 02       MOV  AH, 02H            ; DOS display char function
CD 21       INT  21H                ; write char to console
EB EF       JMP  OUTPUT_STACK       ; continue looping
        EXIT:
C3          RET                     ; return to DOS

D   DB "double$"
T   DB "triple"
W   DB "$oh$","one$","two$","three$","four$","five$","six$","seven$","eight$","nine$"

TL;DR:
The input string is read right to left to make it easier to find a triple.  The output is pushed onto the x86 stack to simplify reversing out the display order and also facilitate rearranging the "double" and "triple" words to precede the digit's name.
If the next digit is different than the last, the name is looked up in the list of words and pushed on to the stack.  Since there's no formal concept of an "indexed array of variable-length strings" in machine code, the list of words is scanned i (the word's index) number of times for the string delimiter ($) to find the corresponding word. Helpfully, x86 does have a pair of short instructions (REPNZ SCASB which is similar to memchr() in C), that simplifies this (thanks CISC!).
If the digit is the same as the previous one, the counter for the length of a "run" is incremented and continues looping leftward on the input.  Once the run is over, the digit's name is taken from the stack since it will need to placed after the "double" or "triple" for each grouping.  If the length of the run is odd (and run length is > 1), the digit's name followed by the string "triple" is pushed to the stack and the run length is reduced by 3.  Since the run length will now be even, the step is repeated for "double" until the run length is 0.
When the input string has reached the end, the stack is dumped out with each saved string written to the screen in reverse order.
I/O:
A standalone PC DOS executable, input from command line output to console.

Download and test PHONE.COM.


Crash (i.e. cause the interpreter to stop working and force close) Python I would like to see who can make Python have a fatal crash with the most creative code. This means that when the program runs, Windows for example, will take over and pop up with something like “IDLE has stopped working”, or Linux will do whatever Linux does when a program crashes.

Rules:

This must be made in Python 2.7 or above (So old bugs aren't exploited that have been fixed in future versions of Python).
The definition of "crash" is "make IDLE or Python exit in an unintended way." This does not mean "make IDLE or Python halt and give a traceback". This also means exit, sys.quit, abort etc are not valid answers. For example, this will not be accepted:

import sys
try:
     print c # Crashes Here, as c is not defined.
 except NameError, SyntaxError:
     print "Oh No!"
     sys.exit()

Making Python stop responding is not accepted.
The code must be explained on what it does to crash. A link to a bug report is fine.

The most upvoted answer after 10 days wins!
Begin!!

EDIT:
May I make it clear that the objective is not to make Python just halt executing the program with a traceback. The objective is to make Python completely crash or stop working. This means that if this task is successfully accomplished, Windows would give this (I'm not crashing Word here, it's just an example of what should happen for a different program):

or this:

Should have been a code-golfing contest ;) - I guess the creativity is the statement the code makes: "I just don't know what's happening here..."

Copy and paste the following character in IDLE running on Windows:

The crash has something to do with the character being encoded as UTF-16 by Windows and the unsuccessful conversion to a UTF-8 character by IDLE...

Edit: python bug #13153


Count even steps of 196 algorithm In the 196-algorithm one starts from an integer and then adds its reverse to it until a palindrome is reached, like this:

start -> 5280
5280 + 0825 = 6105
6105 + 5016 = 11121
11121 + 12111 = 23232
-end-

Write a function that counts how many even numbers are visited before the algorithm ends. Starting and ending numbers are also counted, so, in the example above, visited are consider the numbers: 5280, 6105, 11121, 23232 but not 825, 5016 and 12111.

Examples:

f(5280) = 2
f(56) = 1
f(59) = 1
f(89) = 13

Extended code golf rules apply: shortest number of instructions and operations (like +,-,mod,print,while,if,...) wins.

Python - 10 operations

def f(n):
    q=str(n)
    p=q[::-1]
    return 1-n%2+(q!=p and f(n+long(p)))


Invert a boolean array A nice simple one

Input

Given a boolean array (Or an acceptable alternative), you can assume the array will never be more than 32 elements long.

[false, false, true, false, false]

Output

Invert every element of the array and output it.

[true, true, false, true, true]

Rules

You can write a full program or just a function
Standard loopholes apply
Shortest code in bytes, per language, wins!

Test cases

Input:
[true, false]
Output:
[false, true]

Input: //Example of acceptable alternative
[0,1,1]
Output:
[1,0,0]

05AB1E, 1 byte

Code:

_

Explanation:

_     # Logical not

Try it online!


Convert Binary to Text Your task is to write a program, which takes a binary input and converts it to plain text. For Example:

01100001 01100010 01100011 = "abc"

Rules

Input can come from STDIN, function arguments, command line argument, file, whatever suits you.
The program can be a function, full program,  whatever works, really, as long as no external uncounted code/arguments are needed to run it.
You can assume that the input is valid.
The length of the input is not limited
You can assume that all blocks are seperated with whitespaces

Test Cases

01010100 01100101 01110011 01110100 = "Test"
01001000 01100101 01101100 01101100 01101111 = "Hello"
01010111 01101111 01110010 01101100 01100100 00001101 00001010 = "World"
01000101 01111000 01100001 01101101 01110000 01101100 01100101 00001101 00001010 = "Example"
01100010 01101001 01101110 00001101 00001010 = "bin"

This is code-golf, so the shortest solution wins.

dc, 4 bytes

Needs as input the binary blocks with no separator. This is allowed by the OP.

2i?P

Try it online!

Explanation: using the "abc" example as test case

2i? sets 2 as input radix, then reads the line (output radix is 10 by default). This converts the binary input to decimal: 011000010110001001100011 -> 6382179.
P is a special printing mode that assumes a base 256 number, using its "digits" as ASCII codes: 6382179 = (97 * 256 2) + (98 * 256 1) + (99 * 256 0) -> abc


xkcd 2385 KoTH (Final Exam) Results are now out here!
Congratulations offset prediction for winning the challenge!
Don't worry if you missed out, the controller code as well as all the bots that competed are all in the Github repo, so you can always test your bot against those that competed in the challenge yourself.

(Hover for more info)
This challenge, inspired by the xkcd comic above, is where bots must try to maximise their grades for two subjects: Cybersecurity and Game Theory.
Mechanics
All of the bots presumably have adequate hacking skills to change their own score to whatever they desire within the range of 0-100. This may or may not be due to the fact that the school security systems are rubbish.
Each round, the bots will receive last round's cybersecurity scores in no particular order in an array as input. This is to help make informed decisions about their opponents.
Scoring
The final score for each round is the geometric mean of the two individual scores:

The Cybersecurity score is simply the raw score outputted by the bot.
The Game Theory score is equal to 100 - abs(avg * 0.8 - score) where avg is the average Cybersecurity score and score is the bot's Cybersecurity score.

Using the geometric mean rather than the arithmetic mean is to penalise any strategies that neglect one score to maximise the other.
The score for each round is added to a total score. The bot with the highest total score at the end of the game wins!
Specifications
The challenge is in JS.
Your bot must be an object that has a run method that takes an array of numbers as input and returns a number between 1 and 100 inclusive.
Other rules

Storing data in your bot's properties is allowed, and encouraged!
Using Math.random is allowed.
Using the helper functions sum and average is allowed.
Trying to access any other variables outside your bot's own properties is forbidden.
Standard loopholes apply.

Controller code can be found here.
Example bots
{
  // Example bot
  // It assumes all other bots are greedy and choose 100
  // So it chooses 80
  name: "Simpleton", // Just for fun
  run() {
    return 80
  }
}

{
  // Example bot
  // He assumes everyone will choose the same scores as last round
  // So he chooses 80% of the average last round
  name: "LastRounder",
  own: 0, // Setting properties is allowed
  run(scores) {
    // The average of everyone else's score x 0.8
    this.own = (sum(scores) - this.own) / (scores.length - 1) * 0.8
    return this.own
  }
}

Clarification: Both example bots play in the game as well.
Submissions are due by 11:59pm UTC on Saturday 1 May, but I might be lenient depending on when I'm next online.
If I have made a mistake in my code, feel free to point it out. Thanks

Game Theory is stupid anyway
{
    name: "Game Theory is stupid anyway",
    run: _ => 100
}

Senioritis hits hard sometimes.


Approximate Square Formation Background

I have a bunch of square-shaped boxes of equal size, and since I'm a neat person, I want to arrange them all into a square formation.
However, their number is not necessarily a perfect square, so I may have to approximate the square shape.
I want you to find me the most aesthetically pleasing arrangement -- programmatically, of course.

Input

Your input is a single positive integer k, representing the number of boxes.

Output

Your program shall choose two positive integers m, n such that m*(n-1) < k ≤ m*n holds.
They represent the width and height of the large square-like shape we are arranging.
Since we are looking for aestethically pleasing shapes, the quantity (m - n)2 + (m*n - k)2 shall be minimal, so that the shape is close to a square, and its area is close to k.
If there are still several candidates for the pair (m, n), choose the one where the width m is maximal.

Now, your actual output shall not be the numbers m and n.
Instead, you shall print the arrangement of boxes, using the character # to represent a box.
More specifically, you shall print n-1 rows, each of which consists of m characters #, and then one row of k - m*(n-1) characters #.
Note that the output contains exactly k characters #.

Rules and Scoring

There shall not be any leading or trailing whitespace in the output, except that the last row may be padded with trailing spaces to be of length m, if desired.
There may be one trailing newline, but no preceding newlines.
You may use any printable ASCII character in place of #, if desired.

You may write a full program, or return a string from a function.
The lowest byte count wins, and standard loopholes are disallowed.

Test Cases

Here are the correct outputs for a few input values.

1
#
2
##
3
##
#
4
##
##
8
###
###
##
13
#####
#####
###
17
######
######
#####
18
#####
#####
#####
###
20
#####
#####
#####
#####
21
######
######
######
###
22
######
######
######
####
23
#####
#####
#####
#####
###

Pyth, 28 bytes
jbc*\#Qho.a,,N*NJ_/_QN,JQ_SQ

Try it online.
The crux is that I sort potential m on the following property:
(m - ceil(k/m))^2 + (m*ceil(k/m) - k)^2

Note the total absence of n. The total shape is defined merely by m. Then I transform the above property once more, and my final sorting weight is defined as the Euclidean distance between the following two points:
(m, m*ceil(k/m)) and (ceil(k/m), k)

This changes the weight values, but not their ordering.