Scoring Chinese Hearts Chinese Hearts, also known as Gong Zhu (拱猪, Chase the Pig), is a variance of the Hearts game. It is a 4 player card game with the aim to earn the highest amount of points. You may read more about it on Wikipedia. This time, we want implement a program (full or function) to calculate ones score.

Scoring

The player who plays the highest-value card of the suit that is led wins all cards in this round. And after the game, the score is calculated by these cards:

♥2, ♥3, ♥4 = 0 points for each;
♥5, ♥6, ♥7, ♥8, ♥9, ♥10 = -10 points for each;
♥J = -20 points;
♥Q = -30 points;
♥K = -40 points;
♥A = -50 points;
♠Q = -100 points; ♠Q known as the Pig (猪)
♦J = +100 points; ♦J known as the Goat / Sheep (羊)
♣10 = +50 points along, and x2 with other cards; ♣10 known as the Double / Transformer (变压器)

Special rules:

If a player collects only ♣10, it is worth +50 points. But if a player collects ♣10 together with any other non-zero point cards, it doubles the other cards' points.
If a player collects all hearts ♥2 ~ ♥A (全红), ♥2 ~ ♥A count as +200 points instead of -200 points.
If a player collects all hearts plus ♠Q and ♦J, ♠Q counts as +100 points instead of -100 points.

Scoring rules may vary from place to place. Note that this challenge does not include "sell" (卖/明牌) which would make it more complex.

Input / Output

Input would be a string (or a list of characters).

23456789TJQKA for ♥2 ~ ♥A
P for ♠Q
G for ♦J
D for ♣10

All other cards are ignored from input. You won't get characters out of this list.  We use one deck of cards (52 cards) in this challenge. So, there won't be duplicate cards in the input.

Output as an integer, the score of these cards.

Examples and Testcases

Input            Output
234               0
56789T           -60
T                -10
J                -20
Q                -30
K                -40
A                -50
TJQK             -100
P                -100
G                 100
TJQKP            -200
PG                0
2468TQKG          0
D                 50
234D              50
GD                200
PGD               0
TJQKGD            0
23456789TJQK     -150
3456789TJQKA     -200
23456789TJQKA     200
23456789TJQKAP    100
23456789TJQKAG    300
23456789TJQKAPG   400
2356789TJQKAPD   -600
23456789TJQKAPGD  800
DP2A45968TJK7QG3  800
DP24             -200
G2P6D4           -20

Rule

This is code-golf, shortest codes in bytes win.
Standard loopholes are forbidden.

Note: Some details of scoring rules may be differ from game to game. Some rules allow all hearts plus ♠Q count as +300 points, regardless whether ♦J is collected or not. Some rules apply ♥2, ♥3, ♥4 to ♣10, and collecting ♥2, ♥3, ♥4 together with ♣10 is 0 points instead of +50 points. However, your answer have to follow the rule described in this post.

JavaScript (ES6), 160 156 146 143 135 bytes
Saved 10 bytes thanks to @tsh
Takes input as an array of characters.

a=>(a.map(c=>(i='GPDTJQKA'.search(c))>2|c?t-=h--*c?c>4:i-2:m|=1<<i,m=t=0,h=13),t+=!h*40+(m&2)*(m&!h?5:-5)+m%2*10,t+=m&4?t|m&3?t:5:0)*10

Try it online!
Commented
a => (                     // a[] = input array
  a.map(c =>               // for each card c in a[]:
    (i =                   //   convert c into an index i (-1 to 7)
      'GPDTJQKA'.search(c) //   in the string 'GPDTJQKA'
    ) > 2                  //   if c is a heart symbol (TJQKA)
    | c ?                  //   or c is numeric (2-9):
      t -=                 //     update t (total number of points / 10):
        h--                //       decrement h (number of hearts)
        * c ?              //       if c is numeric:
          c > 4            //         decrement t if c is greater than 4
        :                  //       else:
          i - 2            //         subtract 1 (for Ten) to 5 (for Ace) from t
    :                      //   else:
      m |= 1 << i,         //     update the bitmask m of special cards (G=1, P=2, D=4)
    m = t = 0, h = 13      //   start with m = 0, t = 0 and h = 13
  ),                       // end of map()
  t +=                     // update t (pass #1):
    !h * 40 +              //   add 40 to t if we have all hearts (-(-200) + 200)
    (m & 2) * (            //   if we have the Pig:
      m & !h ?             //     if we have all hearts and the Goat:
        5                  //       add 10 to t (the Pig is worth +100)
      :                    //     else:
        -5                 //       subtract 10 from t (the Pig is worth -100)
    ) +                    //
    m % 2 * 10,            //   add 10 to t if we have the Goat (the Goat is worth +100)
  t +=                     // update t (pass #2):
    m & 4 ?                //   if we have the Double:
      t | m & 3 ?          //     if t is non-zero or we have either the Pig or the Goat:
        t                  //       double t by adding it to itself
      :                    //     else:
        5                  //       add 5 to t (the Double alone is worth +50)
    :                      //   else:
      0                    //     leave t unchanged
) * 10                     // multiply the final result by 10


What's a half on the clock? In my room, I have this geeky clock (click for full size):

Most of these are not difficult to figure out, but the one for 4-o-clock is particularly tricky:

Normally, a fraction like 1/2 doesn't make sense in modular arithmetic since only integers are involved. The correct way, then, is to see this as the inverse of 2, or to put it another way,  is that number  where . Put this way, a moment's thought will reveal that  because .
However, simply finding the multiplicative inverse would be far too easy as a challenge. So let's bump up the difficulty to exponentiation, or in other words, finding the modular logarithm or discrete logarithm of 2. In this case, 3 is the modular logarithm of 2 with respect to 7. For those of you with number theory/abstract algebra background, this means calculating the multiplicative order of 2 modulo n.
The Challenge
Given a positive odd integer n greater than 1, output the smallest positive integer x where .
Examples
n x
3 2
5 4
7 3
9 6
11 10
13 12
15 4
17 8
19 18
21 6
23 11
25 20
27 18
29 28
31 5
33 10
35 12
37 36
39 12
41 20
43 14
45 12
47 23
49 21
51 8
53 52
55 20
57 18
59 58
61 60
63 6
65 12
67 66
69 22
71 35
73 9
75 20
77 30
79 39
81 54
83 82
85 8
87 28
89 11
91 12
93 10
95 36
97 48
99 30
101 100
103 51
105 12
107 106
109 36
111 36
113 28
115 44
117 12
119 24
121 110
123 20
125 100
127 7
129 14
131 130
133 18
135 36
137 68
139 138
141 46
143 60
145 28
147 42
149 148
151 15
153 24
155 20
157 52
159 52
161 33
163 162
165 20
167 83
169 156
171 18
173 172
175 60
177 58
179 178
181 180
183 60
185 36
187 40
189 18
191 95
193 96
195 12
197 196
199 99
201 66

Jelly, 6 bytes

R2*%i1

Try it online!

How it works

R2*%i1  Input: n

R       Range; yield [1, ..., n].
 2*     Compute [2**1, ..., 2**n].
   %    Hook; take all powers modulo n.
    i1  Get the index of the first 1.
        Indices are 1-based, so index k corresponds to the natural number k.


A Semi-palindrome Puzzle An palindrome is a word that is its own reverse.

Now there are some words that might look like palindromes but are not. For example consider the word  sheesh,  sheesh is not a palindrome because its reverse is hseehs which is different, however if we consider sh to be a single letter, then it's reverse is sheesh.  This kind of word we will call a semi-palindrome.

Specifically a word is a semi-palindrome if we can split up the word in to some number of chunks such that when the order of the chunks are reversed the original word is formed.  (For sheesh those chunks are sh e e sh)  We will also require no chunk contains letters from both halves of the word (otherwise every word would be a semi-palindrome).  For example rear is not a semi-palindrome because r ea r has a chunk (ea) that contains letters from both sides of the original word.  We consider the central character in an odd length word to be on neither side of the word, thus for words with odd length the center character must always be in it's own chunk.

Your task will be to take a list of positive integers and determine if they are a semi-palindrome.  Your code should output two consistent unequal values, one if the input is a semi-palindrome and the other otherwise.  However the byte sequence of your code must be a semi-palindrome itself.

Answers will be scored in bytes with fewer bytes being better.

Test-cases

[] -> True
[1] -> True
[2,1,2] -> True
[3,4,2,2,3,4] -> True
[3,5,1,3,5] -> True
[1,2,3,1] -> False
[1,2,3,3,4,1] -> False
[11,44,1,1] -> False
[1,3,2,4,1,2,3] -> False

Program to generate more testcases.

borrible pointed out that these are similar to generalized Smarandache palindromes.  So if you want to do some further reading that's one place to start.

Retina 0.8.2, 85 69 bytes

M`^(.+,)*(\d+,)?(?<-1>\1)*$(?(1)^)|M`^(.+,)*(\d+,)?(?<-1>\1)*$(?(1)^)

Try it online! Explanation:

M`

Selects Match mode. In fact, Retina defaults to Match mode for a single-line program, but the second copy of the code would always match if not for these extra characters.

^

Match must start at the beginning.

(.+,)*

Capture a number of runs of characters. Each run must end in a comma.

(\d+,)?

Optionally match a run of digits and a comma.

(?<-1>\1)*

Optionally match all of the captures in reverse order, popping each one as it is matched.

$

Match must end at the end.

(?(1)^)

Backtrack unless all of the captures were popped. It works by requiring the match to still be at the start of the string if we have an unpopped capture, which is impossible.


What temperature is my stove? My stovetop has 10 (0 through 9) different settings of heat and a very odd way of cycling through them.

It always starts at 0

When I hit plus it increments the number, unless the number is 9 in which case it becomes 0, or the number is 0 in which case it becomes 9.

When I hit minus it decrements the number, unless the number is zero in which case it becomes 4.

There are no other temperature control buttons.
In this challenge you will take as input a string of commands and output which setting my stovetop ends up on after running that sequence.
Answers will be scored in bytes with fewer bytes being better.
Input
You may take input in any of the following formats:

A list/array/vector/stream of booleans/1s or 0s/1s or -1s
A string (or list/array/vector/stream) of two different characters (which should be consistent for your program)

And you may output

An integer on the range 0-9.

A character on the range '0'-'9'.

A string of size 1 consisting of the above.

Testcases
Input as a string - for decrement and + for increment.
 : 0
- : 4
+ : 9
-- : 3
-+ : 5
+- : 8
++ : 0
--- : 2
--+ : 4
-+- : 4
-++ : 6
+-- : 7
+-+ : 9
++- : 4
+++ : 9
---- : 1
---+ : 3

JavaScript (ES6),  38 37  36 bytes
Expects an array of Boolean values, with false for + and true for -. Returns an integer.

a=>a.map(c=>a=a++?c?a-2:a%10:9>>c)|a

Try it online!
Commented
It's important to note that a++ with a = [ true ] is evaluated to NaN because it's first coerced to the string "true" and then to a number. That's why we can safely re-use the array a[] to store the temperature even when we get the singleton [ true ] as input.
a =>             // a[] = input array, re-used to store the temperature
  a.map(c =>     // for each command c in a[]:
    a =          //   update the temperature:
      a++ ?      //     if a is numeric and not equal to 0
                 //     (increment it afterwards):
        c ?      //       if this is a '-':
          a - 2  //         subtract 2
        :        //       else:
          a % 10 //         apply a modulo 10
      :          //     else:
        9 >> c   //       yield 4 if this is a '-', or 9 if this is a '+'
  ) | a          // end of map(); return the final result


Number in Number-squared Consider a sequence of natural numbers for which N appears as a substring in N^2. A018834
Output the nth element of this sequence.
Rules
Program takes only n as input and outputs just one number - N.
The sequence can be 0-indexed or 1-indexed.
Sequence: 1 5 6 10 25 50 60 76 100 250 376 500 600 625 760 ...
Squares:  1 25 36 100 625 2500 3600 5776 10000 62500 141376 250000 360000 390625 577600 ...

This is code-golf so shortest code wins.

Perl 6, 33 31 bytes

-2 bytes thanks to nwellnhof

{(grep {$^a²~~/$a/},1..*)[$_]}

Try it online!

Explanation:

{                            }  # Anonymous code block that returns
 (                      )[$_]   # The nth index of
  grep {          },1..*        # Filtering from the natural numbers
        $^a²                    # If the square of the number
            ~~/$a/              # Contains the number


Codegolf Rainbow : Sorting Colors with Reflection Introduction:
After I posted two rainbow-related challenges: Codegolf Rainbow : Fun with Integer-Arrays 1 and Codegolf Rainbow : Draw in Black-and-White 2, the following comment was made by @ChrisM in the ASCII (Draw in Black-and-White) challenge:

Maybe you know this and it's by design (I know that rainbows are not rhombuses or ascii, too, and higher orders' positions get more complicated), but aren't the colours reversed in the 2nd rainbow?

And he's indeed right. When you see a double rainbow, the second one is actually a reflection of the first, so the colors are reversed. With three rainbows, it's an actual double rainbow, with the third one being a reflection of one of the other two. And with four, there are two rainbows, and two reflections of those.

So, let's make a third related challenge using that fact.
Challenge:
Inputs: A positive integer n which is >=2, and a list of integers of size >= n+1.
Output: The same list ordered as follows:

First split the input lists in sub-lists of size n (where the trailing sub-list could be of any size in the range [1,n]).
Then we do the following based on the amount of sub-lists m:

Sort the first m - m//2 amount of sub-lists from lowest to highest (where // is integer-divide). (I.e. with 6 sub-lists the first three will be sorted from lowest to highest; with 5 sub-lists the fist three will be sorted from lowest to highest.)
Sort the last m//2 amount of sub-lists from highest to lowest (where // is integer-divide). (I.e. with 6 sub-lists the last three will be sorted from highest to lowest; with 5 sub-lists the last two will be sorted from highest to lowest.)

Merge all sub-lists together to form a single list again

Examples:
Inputs: n=7 and [3,2,1,-4,5,6,17,2,0,3,5,4,66,-7,7,6,-5,2,10]
Step 1: [[3,2,1,-4,5,6,17],[2,0,3,5,4,66,-7],[7,6,-5,2,10]]
Step 2: [[-4,1,2,3,5,6,17],[-7,0,2,3,4,5,66],[10,7,6,2,-5]]
Step 3 / Output: [-4,1,2,3,5,6,17,-7,0,2,3,4,5,66,10,7,6,2,-5]
Inputs: n=4 and [7,4,-8,9,3,19,0,-23,-13,13]
Step 1: [[7,4,-8,9],[3,19,0,-23],[-13,13]]
Step 2: [[-8,4,7,9],[-23,0,3,19],[13,-13]]
Step 3 / Output: [-8,4,7,9,-23,0,3,19,13,-13]
Challenge rules:

The integer input n is guaranteed to be larger than 1.
The size of the integer-list is guaranteed to be larger than n.
The trailing sub-list can be smaller than n (as can be seen in the examples and test cases).
I/O format is flexible in any reasonable format. Can be a list/array of integers or decimals, a comma/space/newline delimited string, stream of integers, etc. (Output may not be a 2D list of lists like step 2. Step 3 to flatten it back into a single list is required for this challenge.)

General rules:

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

Test cases:
Inputs: n=7 and [3,2,1,-4,5,6,17,2,0,3,5,4,66,-7,7,6,-5,2,10]
Output: [-4,1,2,3,5,6,17,-7,0,2,3,4,5,66,10,7,6,2,-5]

Inputs: n=4 and [7,4,-8,9,3,19,0,-23,-13,13]
Output: [-8,4,7,9,-23,0,3,19,13,-13]

Inputs: n=2 and [7,-3,1]
Output: [-3,7,1]

Inputs: n=3 and [1,6,99,4,2]
Output: [1,6,99,4,2]

Inputs: n=2 and [5,2,9,3,-5,-5,11,-5,4,12,9,-2,0,4,1,10,11]
Output: [2,5,3,9,-5,-5,-5,11,4,12,9,-2,4,0,10,1,11]

Inputs: n=3 and [5,2,9,3,-5,-5,11,-5,4,12,9,-2,0,4,1,10,11]
Output: [2,5,9,-5,-5,3,-5,4,11,12,9,-2,4,1,0,11,10]

Brachylog, 18 17 16 bytes

ġ₎↔ḍ↔{izo₎ᵐ↔}ᶠcc

Try it online!

-1 byte thanks to @sundar

Expects input as [<integer list>, n]. Note that negative integers are
represented with _, Brachylog's "low minus". Output variable is R.

First time attempting Brachylog, so I imagine it's sub-optimal and ripe for
reducing in bytes.

Explanation

Partition, bifurcate, sort based on index (0: asc, 1: desc), flatten.

ġ₎               | split head of input into groups of length n (last of list)
  ↔              | reverse so that...
   ḍ             | dichotomize splits in two, attaching any additional element to the second list
    ↔            | reverse so first half of partitions corresponds to the 0 index
     {      }    | apply
      i          | : append index
       z         | : zip each sublist with the index of its parent
        o₎ᵐ      | : map over sublists, ordering by the zipped index
           ↔     | : undo earlier reverse
             ᶠ   | find all outputs
              cc | flatten two levels


Electron Configuration In atomic physics and quantum chemistry, the electron configuration is the distribution of electrons of an atom in atomic orbitals. For example, the electron configuration of the neon atom is 1s2 2s2 2p6. (From Wikipedia)

Challenge

Your challenge is to take a number representing the atomic number of an element and output the electron configuration of that element as defined by the Aufbau principle.

Iron (26) has the electron configuration 1s2 2s2 2p6 3s2 3p6 3d6 4s2. However, superscripts are unnecessary; the output for 26 should be along the lines of 1s2 2s2 2p6 3s2 3p6 3d6 4s2.

Specification

You do not have to handle any inputs outside of the range 1 <= n <= 118.
Your output should look something like the test cases, but you may use any non-digit character/characters (aside from s, p, d, and f) to delimit the different orbitals.
You must return/print a string containing the orbital names/values/delmiters; you cannot simply return/print an array.
You do not need to handle any exceptions to the Aufbau principle; where there are exceptions, printing the "incorrect" configuration is fine.

Examples:

Input -> Valid output            -> Invalid output
16    -> 1s2 2s2 2p6 3s2 3p4     -> 1s22s22p63s23p4
16    -> 1s2, 2s2, 2p6, 3s2, 3p4 -> [[1, 2], [2, 2], [2, 6], [3, 2], [3, 4]]
17    -> 1s2+2s2+2p6+3s2+3p5     -> 1s2s2s2s2p6p3s2s3p5

Here is a list of all the electronic orbitals. The maximum values they can contain are below the name:

name: 1s 2s 2p 3s 3p 3d 4s 4p 4d 5s 5p 4f 5d 6s 6p 5f 6d 7s 7p
max:  2  2  6  2  6  10 2  6  10 2  6  14 10 2  6  14 10 2  6

Test Cases

Input -> Output
1     -> 1s1
2     -> 1s2
16    -> 1s2 2s2 2p6 3s2 3p4
50    -> 1s2 2s2 2p6 3s2 3p6 3d10 4s2 4p6 4d10 5s2 5p2
115   -> 1s2 2s2 2p6 3s2 3p6 3d10 4s2 4p6 4d10 5s2 5p6 4f14 5d10 6s2 6p6 5f14 6d10 7s2 7p3

Here is a complete list and a reference implementation of sorts (Try it online!)

Winning Condition

As this is code-golf, the shortest code wins!

Imperative Tampio, 930 bytes

Yöllä on ilot.Olkoon oma ilo uusi yö, jonka iloja ovat ilo"1s",ilo"2s",ilo"2p",ilo"3s",ilo"3p",ilo"3d",ilo"4s",ilo"4p",ilo"4d",ilo"5s",ilo"5p",ilo"4f",ilo"5d",ilo"6s",ilo"6p",ilo"5f",ilo"6d",ilo"7s"ja ilo"7p".Olkoon iso yö uusi yö, jonka iloja ovat 2,2,6,2,6,10,2,6,10,2,6,14,10,2,6,14,10,2 ja 6.Kun iso luku juo ison ilon,iso ilo näyttää oman yön,missä oma yö on oman ilon ensimmäinen ilo ja ujo ilo on ison yön ensimmäinen ilo,jos iso luku on suurempi kuin ujo ilo,niin iso ilo näyttää ujon ilon,iso ilo näyttää ilon" ",oman ilon iloiksi asetetaan oman ilon ilot toisesta alkaen,ison yön iloiksi asetetaan ison yön ilot toisesta alkaen ja iso luku vähennettynä ujolla ilolla juo ison ilon ja,jos iso luku on pienempi tai yhtä suuri kuin ujo ilo,niin iso ilo näyttää ison luvun.Olkoon oma muuttuja uusi muuttuja.Kun iso sivu avautuu,omaan muuttujaan luetaan luku ja oman muuttujan arvo juo ison sivun.

  Yöllä on ilot.Olkoon oma ilo uusi yö, jonka iloja ovat ilo"1s",ilo"2s",ilo"2p",ilo"3s",ilo"3p",ilo"3d",ilo"4s",ilo"4p",ilo"4d",ilo"5s",ilo"5p",ilo"4f",ilo"5d",ilo"6s",ilo"6p",ilo"5f",ilo"6d",ilo"7s"ja ilo"7p".Olkoon iso yö uusi yö, jonka iloja ovat 2,2,6,2,6,10,2,6,10,2,6,14,10,2,6,14,10,2 ja 6.Kun iso luku juo ison ilon,iso ilo näyttää oman yön,missä oma yö on oman ilon ensimmäinen ilo ja ujo ilo on ison yön ensimmäinen ilo,jos iso luku on suurempi kuin ujo ilo,niin iso ilo näyttää ujon ilon,iso ilo näyttää ilon" ",oman ilon iloiksi asetetaan oman ilon ilot toisesta alkaen,ison yön iloiksi asetetaan ison yön ilot toisesta alkaen ja iso luku vähennettynä ujolla ilolla juo ison ilon ja,jos iso luku on pienempi tai yhtä suuri kuin ujo ilo,niin iso ilo näyttää ison luvun.Olkoon oma muuttuja uusi muuttuja.Kun iso sivu avautuu,omaan muuttujaan luetaan luku ja oman muuttujan arvo juo ison sivun.

Online version

It is a very straightforward implementation. In the golfed version I simply replaced the words with short words like ilo, yö, iso, oma, etc.

Ungolfed:

  Listalla on alkiot.

  Olkoon lyhyt orbitaalilista uusi lista, jonka alkioita ovat
      orbitaali "1s",
      orbitaali "2s",
      orbitaali "2p",
      orbitaali "3s",
      orbitaali "3p",
      orbitaali "3d",
      orbitaali "4s",
      orbitaali "4p",
      orbitaali "4d",
      orbitaali "5s",
      orbitaali "5p",
      orbitaali "4f",
      orbitaali "5d",
      orbitaali "6s",
      orbitaali "6p",
      orbitaali "5f",
      orbitaali "6d",
      orbitaali "7s" ja
      orbitaali "7p".

  Olkoon lyhyt maksimilista uusi lista, jonka alkioita ovat
      2,
      2,
      6,
      2,
      6,
      10,
      2,
      6,
      10,
      2,
      6,
      14,
      10,
      2,
      6,
      14,
      10,
      2 ja
      6.

  Kun jaetaan orbitaaleille pienehkö elektronimäärä nykyisellä sivulla,

  nykyinen sivu näyttää nykyisen orbitaalin, missä
      nykyinen orbitaali on lyhyen orbitaalilistan ensimmäinen alkio ja
      nykyinen maksimi on lyhyen maksimilistan ensimmäinen alkio,
  jos pienehkö elektronimäärä on suurempi kuin nykyinen maksimi,
  niin

  nykyinen sivu näyttää nykyisen maksimin,
  nykyinen sivu näyttää välin " ",
  lyhyen orbitaalilistan alkioiksi asetetaan lyhyen orbitaalilistan alkiot toisesta alkaen,
  lyhyen maksimilistan alkioiksi asetetaan lyhyen maksimilistan alkiot toisesta alkaen
  ja  jaetaan orbitaaleille pienehkö elektronimäärä vähennettynä nykyisellä maksimilla nykyisellä sivulla,

  ja, jos pienehkö elektronimäärä on pienempi tai yhtä suuri kuin nykyinen maksimi,

  niin
  nykyinen sivu näyttää pienehkön elektronimäärän.

  Olkoon mukava muuttuja uusi muuttuja.

  Kun nykyinen sivu avautuu,

  mukavaan muuttujaan luetaan luku
  ja  jaetaan orbitaaleille mukavan muuttujan arvo nykyisellä sivulla.

Online version

Translation:

  A list has items.

  Let the short orbital list be a new list, its items are
  the orbital "1s",
  the orbital "2s",
  the orbital "2p",
  the orbital "3s",
  the orbital "3p",
  the orbital "3d",
  the orbital "4s",
  the orbital "4p",
  the orbital "4d",
  the orbital "5s",
  the orbital "5p",
  the orbital "4f",
  the orbital "5d",
  the orbital "6s",
  the orbital "6p",
  the orbital "5f",
  the orbital "6d",
  the orbital "7s" and
  the orbital "7p".

  Let the short maximum list be a new list, its items are
  2,
  2,
  6,
  2,
  6,
  10,
  2,
  6,
  10,
  2,
  6,
  14,
  10,
  2,
  6,
  14,
  10,
  2 and
  6.

  When a small number of electrons is divided to the orbitals at the current page,

  the current page shows the current orbital, where the current orbital is the first item in the short orbital list and the current maximum is the first element in the short maximum list,
  if the small number of electrons is greater than the current maximum,

  the current page shows the current maximum,
  the current page shows the space " ",
  the elements of the short orbital list are set to be the elements of the short orbital list beginning from the second,
  the elements of the short maximum list are set to be the elements of the short maximum list beginning from the second
  and the small number of electrons subtracted by one is divided to the orbitals at the current page,

  and, if the small number of electrons is less than or equal to the current maximum,

  the current page shows the small number or electrons.

  Let the nice variable be a new variable.

  When the current page opens,

  a number is read to the nice variable
  and the value of the nice variable is divided to the orbitals at the current page.

The translation is approximate, I had to change the word order to make the English more natural.


Transpile Brainstract to Brainfuck Introduction
Brainstract, a newly created dialect of Brainfuck adds a bit more elements to the syntax. In addition to the normal Brainfuck syntax, there are macros. To define a macro:
{macro_name ++++}

Then use it:
{macro_name} Adds 4 to the current cell

Challenge
Your challenge is to take a valid Brainstract program as input (command-line-arguments, function arguments, STDIN or file), and output a valid Brainfuck program that is equivalent to the Brainstract program (non-brainfuck characters are allowed in output). You may assume all input will be valid Brainstract.
Brainstract Spec
Whitespace counts as ANY whitespace (tabs, spaces, etc.)
A macro is defined by an opening brace character ({) followed by a macro name which must be made up of any characters except whitespace, brainfuck, and Brainstract characters (anything except whitespace and {}[]<>+-.,)
Then, it is followed by any amount of whitespace and a macro definition, made up of macro calls and non-brace characters and finally the macro is closed off with a closing brace (})
A macro call is of the form {macro_name} where macro name is the same as above.

Examples
Format: Input -> Output
{cat ,.} {cat}{cat}{cat}            -> ,.,.,.
{add [>+<-]} ++++>+<{add}           -> ++++>+<[>+<-]
{recursive ,.{recursive}}           -> (undefined behavior)
++++ {decrement -} ++++ {decrement} -> ++++++++-
{a >>>---<<<} {b {a}{a}} {b}        -> >>>---<<<>>>---<<<

Standard Loopholes apply, and shortest code wins

JavaScript (Node.js), 113 108 102 bytes

-5 bytes because input will always be valid brainstract
-6 bytes thanks to Cows quack for regex function golfs

x=>{while(m=/({\w+)\s+(\W+)}/.exec(x))x=x.replace(eval(`/${m[1]}}/g`),m[2]).replace(m[0],'');return x}

Try it online!

TIO Link includes a test suite of all 4 "valid" test cases provided in the OP.
The invalid recursive macro test was ignored as, given it's undefined behavior and our program can whatever, there's no need to test it; the result is irrelevant.

Ungolfed Explanation:

fun = code => {
    // While there's a macro definition in the code
    while(match = /{(\w+)\s+(\W+)}/.exec(code)) {
        // Replace calls to the macro with the macro's code
        code = code.replace(eval(`/${m[1]}}/g`),m[2])
        // And remove the definition from the code
            .replace(m[0],'');
    }
    // Remove all spaces from the code and return
    return x;
}

The entire function relies on the regex: /{(\w+)\s+(\W+)}/
This should match any valid macro definition and include the macro name in Capture Group 1, and the macro's code in Capture Group 2.

Due to how JS's regex.exec() returns, m[0] is the whole matched string (the entire macro definition), m[1] is the string matched by Capture Group 1 (the macro name) and m[2] is the string matched by Capture Group 2 (the macro's code)

We can then replace all instances of {m[1]} with m[2], then remove the first instance of m[0] in order to remove the macro definition. This is required in part due to the way brainfuck would interpret the macro definition, and in part due to the way the while loop in this function works (it finds the first definition in the code, if we don't remove the definition after we've processed it, it'll keep finding the first definition over and over)

However, our first capture group m[1] also includes the opening brace { of the macro definition. This is so that when replacing {m[1]} with m[2], we actually only need to replace m[1]}, which saves a byte.

Unfortunately including a variable m[1] in a RegExp in JS is a bit costly, as we need to eval the regex, which adds 6 bytes.

There's probably quite a bit of golfing room in this answer, as there tends to me in my NodeJS answers.
If anybody has any suggestions for golfing, let me know in the comments.

However if your answer involves using an entirely different approach to mine, please post your own answer :)


I'm symmetric, not palindromic! Background

Inspired by I'm a palindrome. Are you?, where it is presented the shocking fact that “()() is not a palindrome, but ())(”, I asked myself what instead is ()() and the answer is simply: it is a string with a vertical symmetry axis!

The task

Write a program or function that takes a string S (or the appropriate equivalent in your language) as input, checks for symmetry along the vertical axis, and returns a truthy or falsy value accordingly. You can use any reasonable means to take the input and provide the output.

Reflectional symmetry

Reflectional symmetry around a vertical axis (or left-right symmetry) means that if you put a mirror vertically at the exact center of the string, the reflected image of the first half of the string is identical to the second half of the string.

For example, the following strings are reflectional symmetric around a vertical axis:

()()
()()()
[A + A]
WOW ! WOW
OH-AH_wx'xw_HA-HO
(<<[[[T*T]]]>>)
(:)
)-(
())(()
qpqp

while the following are not:

())(
((B))
11
+-*+-
WOW ! wow
(;)
qppq

Rules of the contest

• Your program or function will receive only printable ASCII characters. You can include or not the empty string, (which is symmetric, of course!) as legal input, which is better for you.

• The ASCII characters that can be considered symmetric with respect to the vertical axes are the following (note the initial space, and the difference between uppercase and lowercase letters):

 !"'+*-.:=AHIMOTUVWXY^_ovwx|

The ASCII characters that can be considered “mirrored” and their corresponding characters are:

()<>[]{}qpbd/\

Note that, since they are mirrored, you can have both () as well as )(, /\ and \/, etc.

All the other ASCII printable characters must be considered asymmetric and without a mirrored corresponding character.

• This is a code-golf challenge: the shorter your program is, measured in bytes, the better, in any programming language.

• Kudos to people that will produce a symmetric program!

Note: this question is not a duplicate of "Convenient Palindrome”, that requires to check for palindromic strings in which parentheses are flipped. This question is different for two reasons:

1) it is a restriction of the other question for what concerns non-parentheses characters, since only symmetric characters can appear in reverse order.

2) Since it is based on the concept of symmetry, and not on a concept of “convenient palindrome”, mirrored characters can appear in both order, i.e. [] and ][, and this makes the program to solve it different from programs that solve the other problem.

JavaScript (ES6), 130 125 113 bytes

f=
s=>s==[...s].reverse(s=`()<>[]{}qpbd/\\`).map(c=>s[s.indexOf(c)^1]||/[- !"'+*.:=AHIMOT-Y^_ovwx|]/.exec(c)).join``
<input oninput=o.textContent=f(this.value)><pre id=o>

Edit: Saved 5 bytes thanks to @Arnauld. Saved a further 11 bytes thanks to @YairRand.


Python 2, 166 bytes

def Q(x,n,a=0):
 e=n/2
 while pow(a*a-x,e,n)<2:a+=1
 w=a*a-x;b=r=a;c=s=1
 while e:
    if e%2:r,s=(r*b+s*c*w)%n,r*c+s*b
    b,c=(b*b+c*c*w)%n,2*b*c;e/=2
 return min(r,-r%n)


Solve the chromatic puzzle Over at our friends at Puzzling.SE, the following puzzle was posted: Is this chromatic puzzle always solvable? by Edgar G. You can play it here.

Puzzle explanation

Given a m x n grid with tiles of three different colours, you may select any two adjacent tiles, if their colours are different. These two tiles are then converted to the third colour, i.e., the one colour not represented by these two tiles. The puzzle is solved if all tiles have the same colour. Apparently, one can prove that this puzzle is always solvable, if  neither m nor n are divisible by 3.

Of course, this begs for a solving algorithm. You will write a function or program that solves this puzzle. Note that functions with 'side effects' (i.e., the output is on stdout rather than in some awkward data type return value) are explicitly allowed.

Input & Output

The input will be an m x n matrix consisting of the integers 1, 2 and 3 (or 0, 1, 2 if convenient). You may take this input in any sane format. Both m and n are >1 and not divisible by 3. You may assume the puzzle is not solved

You will then solve the puzzle. This will involve a repeated selection of two adjacent tiles to be 'converted' (see above). You will output the two coordinates of these tiles for each step your solving algorithm took. This may also be in any sane output format. You are free to choose between 0-based and 1-based indexing of your coordinates, and whether rows or columns are indexed first. Please mention this in your answer, however.

Your algorithm should run within reasonable time on the original 8x8 case. Brute-forcing it completely is explicitly disallowed, i.e. your algorithm should run under O(k^[m*(n-1)+(m-1)*n]) with k the number of steps needed for the solution. The solution however is not required to be optimal. The proof given in the linked question may give you an idea as to how to do this (e.g., first do all columns using only vertically adjacent tiles, and then do all rows)

Test cases

In these test cases, the coordinates are 1-based and rows are indexed first (like MATLAB/Octave and probably many others).

Input:
[1 2]
Output: (result: all 3's)
[1 1],[1,2]

Input:
[ 1 2
  3 1 ]
Output: (result: all 1's)
[1 1],[2 1]        (turn left column into 2's)
[2 1],[2 2]        (turn right column into 3's)
[1 1],[1 2]        (turn top row into 1's)
[2 1],[2 2]        (turn bottom row into 1's)

Input:
[1 2 3 2
 3 2 1 1]

Output: (result: all 3's)
[1 1],[1 2]
[1 3],[1 4]
[1 2],[1 3]
[1 1],[1 2]
[1 2],[1 3]
[1 1],[1 2]
[1 3],[1 4]
[2 1],[2 2]
[1 1],[2 1]
[1 2],[2 2]
[1 3],[2 3]
[1 4],[2 4]

If desired, I may post a pastebin of larger test cases, but I think this should be sufficient.

Octave, 334 313 bytes

Since the challenge may seem a bit daunting, I present my own solution. I did not formally prove that this method works (I guess that will come down to proving that the algorithm will never get stuck in a loop), but so far it works perfectly, doing 100x100 testcases within 15 seconds. Note that I chose to use a function with side effects rather than one that returns all the coordinates since that saved me a few bytes. Coordinates are row-major, 1-based, and formatted as row1 col1 row2 col2. Input colours are 0,1,2 since this works better with mod, at the cost of having to use numel rather than nnz. Golfed version: Edit: saved another few bytes by using a technique from Kevin Lau's answer.

function P(p)
k=0;[m,n]=size(p);t=@(v)mod(sum(v)*numel(v),3);for c=1:n
p(:,c)=V(p(:,c));end
k=1;for r=1:m
p(r,:)=V(p(r,:));end
function a=V(a)
while any(a-(g=t(a)))
isempty(q=find(diff(a)&a(1:end-1)-g,1))&&(q=find(diff(a),1));
a([q q+1])=t(a([q q+1]));if k
disp([r q r q+1])
else
disp([q c q+1 c])
end;end;end;end

Example GIF of the solving algorithm:

Ungolfed version:

function solveChromaticPuzzle(p)
[m,n]=size(p);                           % Get size
t=@(v)mod(sum(v)*numel(v),3);            % Target colour function
for c=1:n                                % Loop over columns
    p(:,c)=solveVec(p(:,c));             % Solve vector
end
for r=1:m                                % Loop over rows
    p(r,:)=solveVec(p(r,:));
end
    function a=solveVec(a)               % Nested function to get globals
        g=t(a);                          % Determine target colour
        while(any(a~=g))                 % While any is diff from target...
            % Do the finding magic. Working left-to-right, we find the
            % first pair that can be flipped (nonzero diff) that does not
            % have the left colour different from our goal colour
            q=min(intersect(find(diff(a)),find(a~=g)));
            if(isempty(q))               % In case we get stuck...
                q=find(diff(a),1);       % ... just flip the first possible
            end;
            a([q q+1])=t(a([q q+1]));    % Do the actual flipping.
            if(exist('r'))               % If we're working per row
                disp([r q r q+1])        % Print the pair, using global row
            else
                disp([q c q+1 c])        % Print the pari, using global col
            end
        end
    end
end


Divide and stay Happy. Who cares about the Conquer part? Well, when I buy gifts for my two wives, I want them to feel equally important to me, but it's hard to go shopping with fixed budgets. Instead, I buy a bunch of stuff and divide them into two groups with as equal value as possible. Then I buy a bunch of chocolates to fix the rest.

But I don't want do all the hard lifting when my computer can do it. And you don't either. So solve this problem so that the next time you need to divide gifts among your wives, you know it would be easy.

Input

1 array of (N*2) elements where N*2 is specified in the 1st line.
The elements of the array in the following line.

Output

2 array of N elements each such that:
Difference of (Sum of elements of array 1) and (Sum of elements of array 2) is as close as possible to 0.

Example

Input

4
1 2 3 4

Output

1 4
2 3
diff=0

Disclaimer: I don't have two wives. But when I feel bad, I imagine having two wives. And suddenly, I am thankful and happy that I have only one. :D

Java

Trying to solve this problem in two phases:

Build two equally sized lists by adding the remaining biggest to the currently smaller list and the next to the other. Repeat.
Identify items from both lists that can be switched to reduce the difference in value

Input like

8
1 2 3 4 5 6 7 8

is already solved after phase 1 as e.g.

2 3 5 8
1 4 6 7
diff=0

and input like

6
1 4 5 6 7 8

will need both phases so that

1 5 8
4 6 7
diff=3

(after phase one) becomes the result of

1 6 8
4 5 7
diff=1

While I can guarantee this attempt will always provide a solution, I can not prove that a optimal solution is found in all cases. With the restriction of equally sized lists it however feels quite realistic that there are no corner cases left behind. Prove me wrong ;-)
Program on ideone.com
import java.util.*;

/**
 * Created to solve http://codegolf.stackexchange.com/q/23461/16293 .
 */
public class EqualSums {

    public static void main(String[] args) {
        final Scanner s = new Scanner(System.in);
        // Read number of elements to divide
        final int count = s.nextInt();
        if (count % 2 == 1) {
            throw new IllegalStateException(count + " can not be divided by 2. Consider adding a 0 value.");
        }
        // Read the elements to divide
        final SortedList valueStack = new SortedList(count);
        for (int i = 0; i < count; i++) {
            valueStack.add(s.nextLong());
        }

        final SortedList targetOne = new SortedList(count / 2);
        final SortedList targetTwo = new SortedList(count / 2);
        // Divide elements into two groups
        addInPairs(targetOne, targetTwo, valueStack);
        // Try to ensure groups have equal value
        retaliate(targetOne, targetTwo);

        // Output result
        System.out.println(targetOne);
        System.out.println(targetTwo);
        System.out.println("diff=" + Math.abs(targetOne.getSum() - targetTwo.getSum()));
    }

    private static void addInPairs(SortedList targetOne, SortedList targetTwo, SortedList valueStack) {
        SortedList smallerTarget = targetOne;
        SortedList biggerTarget = targetTwo;
        while (!valueStack.isEmpty()) {
            // Add biggest remaining value to small target
            smallerTarget.add(valueStack.removeLast());

            // Add second biggest remaining value to big target
            biggerTarget.add(valueStack.removeLast());

            // Flip targets if roles have changed
            if (smallerTarget.getSum() > biggerTarget.getSum()) {
                final SortedList temp = smallerTarget;
                smallerTarget = biggerTarget;
                biggerTarget = temp;
            }
        }

    }

    private static void retaliate(SortedList targetOne, SortedList targetTwo) {
        long difference;
        boolean changed;
        outer:
        do {
            difference = Math.abs(targetOne.getSum() - targetTwo.getSum());
            if (difference == 0) {
                return;
            }
            changed = false;
            // Try to find two values, that reduce the difference by changing them between targets
            for (Long valueOne : targetOne) {
                for (Long valueTwo : targetTwo) {
                    final Long tempOne = targetOne.getSum() + valueTwo - valueOne;
                    final Long tempTwo = targetTwo.getSum() - valueTwo + valueOne;
                    if (Math.abs(tempOne - tempTwo) < difference) {
                        targetOne.remove(valueOne);
                        targetTwo.add(valueOne);
                        targetTwo.remove(valueTwo);
                        targetOne.add(valueTwo);
                        changed = true;
                        continue outer;
                    }
                }
            }
        } while (changed);
    }

    public static class SortedList extends AbstractList<Long> {

        private final ArrayList<Long> list;
        private long sum = 0;

        public SortedList(int count) {
            list = new ArrayList<>(count);
        }

        // the next functions access list-field directly
        @Override
        public Long get(int index) {
            return list.get(index);
        }

        @Override
        public boolean add(final Long t) {
            final int i = Collections.binarySearch(list, t);
            if (i < 0) {
                // No equal element present
                list.add(-i - 1, t);
            } else {
                list.add(afterLastEqual(i, t), t);
            }
            sum += t;
            return true;
        }

        @Override
        public Long remove(int index) {
            final Long old = list.remove(index);
            sum -= old;
            return old;
        }

        @Override
        public int size() {
            return list.size();
        }

        // the next functions access list-field only through the functions above this point
        // to ensure the sum is well kept

        public long getSum() {
            return sum;
        }

        private int afterLastEqual(final int start, Object o) {
            int found = start;
            while (found < size() && o.equals(get(found))) {
                found++;
            }
            return found;
        }

        private int beforeFirstEqual(final int start, final Object o) {
            int found = start;
            while (found >= 0 && o.equals(get(found))) {
                found--;
            }
            return found;
        }

        @Override
        public int indexOf(Object o) {
            try {
                final int i = Collections.binarySearch(this, (Long) o);
                if (i >= 0) {
                    return beforeFirstEqual(i, o) + 1;
                }
            } catch (ClassCastException e) {
                // Object was not instance of Long
            }
            return -1;
        }

        @Override
        public int lastIndexOf(Object o) {
            try {
                final int i = Collections.binarySearch(this, (Long) o);
                if (i >= 0) {
                    return afterLastEqual(i, o) - 1;
                }
            } catch (ClassCastException e) {
                // Object was not instance of Long
            }
            return -1;
        }

        @Override
        public boolean remove(Object o) {
            if (o == null) {
                return false;
            }
            final int i = indexOf(o);
            if (i >= 0) {
                remove(i);
                return true;
            }
            return false;
        }

        public Long removeLast() {
            return remove(size() - 1);
        }

        public Long removeFirst() {
            return remove(0);
        }

        @Override
        public String toString() {
            Iterator<Long> it = iterator();
            if (!it.hasNext()) {
                return "";
            }

            StringBuilder sb = new StringBuilder();
            for (; ; ) {
                Long e = it.next();
                sb.append(e);
                if (!it.hasNext()) {
                    return sb.toString();
                }
                sb.append(' ');
            }
        }
    }
}


Jelly, 10 bytes

Œgœ^/€FµÐL

Try it online!

How it works

Œgœ^/€FµÐL  Main link. Argument: A (array)

       µ    Combine all links to the left into a chain.
Œg              Group all adjacent equal items.
    /€          Reduce each group by...
  œ^                symmetric multiset difference.
                In each step, this maps ([], n) to [n] and ([n], n) to [], so the
                group is left with a single item if its length is odd, and no items
                at all if its length if even.
      F         Flatten the resulting array of singleton and empty arrays.
        ÐL  Apply the chain until the results are no longer unique. Return the last
            unique result.


Look mom! I made my own (Base 10) numeral system! We've all done it, well, maybe not, but making your own alien language and numbering system is a staple of especially fantasy writing, but is mostly just a fun activity.

The task is simple, take two inputs:

An ordered list input of 10 [ten] unique 'numerals' (any printable
ASCII character) and interpret them, in order, as the values 0, 1,
2, 3,...,9

+There are exceptions to what can be a numeral here. Arithmetic operators (+, -, *, /), Parentheses, and spaces cannot be used as one of the numerals.
An arithmetic problem using only those 'numerals'

And output the equivalent integer result in the given form.

Here's an example:

INPUT

abcdefghij

bcd + efg + hij

OUTPUT

bdgi

In the example, the input list (you may choose which form the list comes in) of 'abcdefghij' corresponds to '0123456789' just as 'hjkloiwdfp' would also correspond 1 to 1 with '0123456789' where instead of 'a' associating with zero, 'h' does. The arithmetic following 'translates' to 123 + 456 + 789, which equals 1368. This must then be outputted in the form we gave it, so b (which represents 1) d (for 2) g (for 6) and i (for 8).

TEST CASES

abcdefghij
abc + def - ghij

-gedc

qwertyuiop
qwerty / uiop

e

%y83l;[=9|
(83l * 9) + 8%

y9|8

MORE RULES

Standard
Loopholes
are forbidden!
This is code golf, so shortest answers in bytes wins.
Must be a full program or function taking the inputs and outputs in whatever format works best for you. (Just cannot add additioal information in the inputs, just 'numerals' and the expression.
Use any language you'd like (as long as it complies with other rules)

05AB1E, 10 9 bytes
žh‡.Eò¹Åв

(Now) outputs as a list of characters.
Try it online or verify all test cases.
Explanation:

  ‡        # Transliterate the second (implicit) input, replacing every character of
           # the first (implicit) input with:
žh         # The builtin "0123456789"
   .E      # Then evaluate it as Elixir code
     ò     # Round it to the nearest integer
      ¹Åв  # And change it back by using a custom base-conversion with the first input as
           # base (which results in a character list)
           # (after which that result is output implicitly)

The new version of 05AB1E is build is build in Elixir. The .E function will call call_unary(fn x -> {result, _} = Code.eval_string(to_string(x)); result end, a), where the Code.eval_string is an Elixir builtin.
Note that the legacy version of 05AB1E won't work for this, because it is build in Python. The numbers with leading 0s won't be evaluated:
See all test cases in the legacy version (which uses the 10-byte version because the Åв builtin is new).


Parse nested digit-lead strings The task

A string S is constructed with the following process:

Start with S being the empty string.
Insert at some position of S a string of the form ds, where d is a nonzero digit and s is a string of d lowercase ASCII letters. We say ds is a constituent of S.
Go to step 2 or stop.

Your task is to take such a string as input, and output its constituents concatenated into a single string, in the order of appearance of their leading digits.
The output must be a single string, and there can't be any delimiters (including newlines) between the constituents.
You can choose whether the input and output strings have quotes.
Note that the input and output will never be empty.

Example

Let's construct a string with the above process.
The structure of the constituents is highlighted in the final result.

S = ""              // Insert "3abc"
S = "3abc"          // Insert "2gh" after 'a'
S = "3a2ghbc"       // Insert "1x" before '3'
S = "1x3a2ghbc"     // Insert "3tty" after '3'
S = "1x33ttya2ghbc" // Final result
     └┘│└┴┴┘│└┴┘││
       └────┴───┴┘

The output is obtained by concatenating the constituents in the order of their digits.
In this case, the correct output is

"1x3abc3tty2gh"

Rules and scoring

You can write a full program or a function.
the lowest byte count wins, and standard loopholes are disallowed.

Test cases

1k -> 1k
4asdf -> 4asdf
111xyz -> 1z1y1x
8whatever3yes -> 8whatever3yes
8what3yesever -> 8whatever3yes
1x33ttya2ghbc -> 1x3abc3tty2gh
63252supernestedstrings2ok -> 6trings3eds2st5perne2su2ok
9long3yes4lo2ngwords11here -> 9longrdsre3yes4lowo2ng1e1h
9abc8de7fg6hi5jk4lm3o2pq1rstuvwxyzabcdefghijklmnopqrst -> 9abcopqrst8deijklmn7fgdefgh6hizabc5jkwxy4lmuv3ost2pq1r

JavaScript (ES6), 68 bytes

f=s=>s&&f(s.replace(/\d\D+$/,m=>(s=m.slice(0,i=++m[0]),m.slice(i))))+s

Explanation

Based on a simple concept:

Match the last digit n followed by n letters in the input string
Remove it from the input string and add it to the start of the output string
Repeat until the input string is empty

Recursion was the shortest way to do this in JavaScript.

f=s=>
  s&&                        // if the input string is empty, return the empty string
  f(                         // prepend the constituent before it
    s.replace(/\d\D+$/,m=>(  // match the last digit followed by every remaining letter
      s=m.slice(0,n=++m[0]), // set s to the constituent (n followed by n letters)
                             // (we must use s because it is our only local variable)
      m.slice(n)             // replace the match with only the letters after it
    ))
  )+s                        // append the constituent
<input type="text" id="input" value="9long3yes4lo2ngwords11here" />
<button onclick="result.textContent=f(input.value)">Go</button>


Prime Modified Z-Factorials Let me explain one by one the above terms...
We will call \$\text{Z-Factorial}(n)\$ of a positive integer \$n\$, \$n!\$ (i.e. \$n\$ factorial) without any trailing zeros.
So, \$\text{Z-Factorial}(30)\$ is \$26525285981219105863630848\$ because \$30!=265252859812191058636308480000000\$
We will call Modified Z-Factorial of \$n\$, the \$\text{Z-Factorial}(n) \mod n\$.
So, Modified Z-Factorial of \$30\$, is \$\text{Z-Factorial}(30) \mod 30\$ which is \$26525285981219105863630848 \mod 30 = 18\$
We are interested in those \$n\$'s for which the Modified Z-Factorial of n is a Prime Number
Example
The number \$545\$ is PMZ because \$\text{Z-Factorial}(545) \mod 545 = 109\$ which is prime
Here is a list of the first values of \$n\$ that produce Prime Modified Z-Factorial (PMZ)
5,15,35,85,545,755,815,1135,1165,1355,1535,1585,1745,1895,1985,2005,2195,2495,2525,2545,2615,2705,2825,2855,3035,3085,3155,3205,3265,3545,3595,3695,3985,4135,4315,4385,4415,4685,4705,4985,5105,5465,5965,6085,6155,6185,6385,6415,6595...

Task
The above list goes on and your task is to find the \$k\$th PMZ
Input
A positive integer \$k\$
Output
The \$kth\$ PMZ
Test Cases
here are some 1-indexed test cases.
Please state which indexing system you use in your answer to avoid confusion.
Your solutions need only work within the bounds of your language's native integer size.
input -> output
 1        5
 10       1355
 21       2615
 42       5465
 55       7265
 100      15935
 500      84815

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

Jelly,  13  11 bytes
!Dt0Ḍ%⁸Ẓµ#Ṫ

A full program reading from STDIN which prints the result to STDOUT.
Try it online!
How?
!Dt0Ḍ%⁸Ẓµ#Ṫ - Main Link: no arguments
         #  - set n=0 (implicit left arg) and increment getting the first
                (implicit input) values of n which are truthy under:
        µ   -   the monadic chain (f(n)):
!           -     factorial -> n!
 D          -     convert from integer to decimal digits
  t0        -     trim zeros
    Ḍ       -     convert from decimal digits to integer
      ⁸     -     chain's left argument, n
     %      -     modulo
       Ẓ    -     is prime?
          Ṫ - tail
            - implicit print


Is it a Sphenic Number? A Sphenic Number is a number that is the product of exactly three distinct primes. The first few Sphenic numbers are 30, 42, 66, 70, 78, 102, 105, 110, 114. This is sequence A007304 in the OEIS.

Your Task:

Write a program or function to determine whether an inputted integer is a Sphenic number.

Input:

An integer between 0 and 10^9, which may or may not be a Sphenic Number.

Output:

A truthy/falsy value indicating whether the input is a Sphenic Number.

Examples:

30  -> true
121 -> false
231 -> true
154 -> true
4   -> false
402 -> true
79  -> false
0   -> false
60  -> false
64  -> false
8   -> false
210 -> false

Scoring:

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

bash, 43 bytes

factor $1|awk '{print $2-$3&&$3-$4&&NF==4}'

Try it online!

Input via command line argument, outputs 0 or 1 to stdout.

Fairly self-explanatory; parses the output of factor to check that the first and second factors are different, the second and third are different (they're in sorted order, so this is sufficient), and there are four fields (the input number and the three factors).


A Triangular Slice of Squared Pi Inspired by Bake a slice of Pi

Challenge

Given input 3 <= n <= 100 and 3 <= y <= n, construct an n x n matrix of the decimal portion of pi (14159...), starting in the top left. Then, take the upper-right triangle of size y x y and concatenate it together. Output the resulting number.

For example, for input n = 5, y = 3, the following matrix is constructed

14159
26535
89793
23846
26433

Then, the upper-right 3 x 3 triangle would be

159
 35
  3

so 159353 is the output.

Input

Two integers -- n representing the size of the square matrix of the digits of pi, and y representing the upper-right triangle -- in any convenient format.

Output

The resulting sliced and concatenated number, either printed/displayed to the screen, returned as a string, etc.
Trailing/leading whitespace is optional, so long as there's no whitespace in the output (i.e., 159 35  3 or the like would be invalid).
Note that since we're explicitly looking for the digits of pi, and not an approximation or mathematical calculation, answers should not round the final digit of the matrix.

Rules

This is code-golf so all the usual rules for golfing apply, and the shortest code (in bytes) wins.
Either a full program or function are acceptable.
Standard loopholes are forbidden.

Examples

 n  y  output
-------------
 3  3  141923
 5  3  159353
 6  4  1592589383
 6  6  141592535893238643794
20 12  358979323846950288419715820974944628620899211706792306647223172745025559196615

05AB1E, 19 bytes

Uses CP-1252 encoding.

nžs¦¦¹ôI£íRvyN>£J}R

Try it online!

Explanation

n=5, y=3 used for example

nžs                  # push pi to n^2 digits
                     # STACK: 3.1415926535897932384626433
   ¦¦                # remove the first 2 chars
                     # STACK: 1415926535897932384626433
     ¹ô              # split into n*n matrix
                     # STACK: ['14159', '26535', '89793', '23846', '26433']
       I£            # keep the first y rows
                     # STACK: ['14159', '26535', '89793']
         íR          # reverse the list of rows and each individual row
                     # STACK: ['39798', '53562', '95141']
           v     }   # for each y,N (row, index) in the list
            yN>£J    # keep the first index+1 digits of the row and join to string
                     # STACK: 353951
                  R  # reverse the string
                     # STACK: 159353
                     # implicit print


Implement the Fibonacci sequence... Shifted to the right Background
We all know the famous Fibonacci sequence, where each term is the sum of the previous two, with the first term being 0 and the second one being 1. The first few elements are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765

What we are going to implement today is a similar sequence, starting at 0 and 1 as well, and each term is the sum of the previous two, but the sum's digits are shifted by one place to the right. What does "shifted" mean? – A digit shifted to the right is basically that digit + 1, unless it equals 9, which maps to 0 instead. Just as a reference, here is the full list of mappings:
0 -> 1;  1 -> 2;  2 -> 3;  3 -> 4;  4 -> 5;  5 -> 6;  6 -> 7;  7 -> 8;  8 -> 9;  9 -> 0

With all that being said, these are the first terms of our Fibonacci-shifted sequence:
0, 1, 2, 4, 7, 22, 30, 63, 4, 78, 93, 282, 486, 879, 2476, 4466, 7053, 22620, 30784, 64515

Given an integer N (non-negative if 0-indexed and positive if 1-indexed), finds the Nth term of the Fibonacci-shifted sequence.
Rules

The output may contain leading zero(es), in case 9 is the first (few) digit(s).

Input and output can be handled using any default mean.

Take note that Loopholes are forbidden.

This is code-golf, hence your program will be scored in bytes, with less bytes being better.

Python 2, 78 72 bytes

f=lambda n:n>1and int(''.join(`-~int(i)%10`for i in`f(n-1)+f(n-2)`))or n

Try it online!

Saved 6 bytes thanks to Halvard Hummel.


Equal numbers in sub-array Given an array of numbers with length >=3 and length % 3 == 0

[1, 2, 3, 4, ...]

You will split it in sub-arrays of length 3

[[1, 2, 3], [4, 5, ...], [...

And return an array with

[0] => The amount of cases in the sub-array where all numbers are equal
[1] => In case all numbers in sub-array are not equal, the amount of cases in the sub-array where only 2 numbers are equal

Example and test cases:

Input: [2, 4, 2, 5, 5, 5, 4, 2, 1, 3, 3, 1] output [1, 2]

This is because

[[2, 4, 2], [5, 5, 5], [4, 2, 1], [3, 3, 1]]
  ^     ^    ^  ^  ^               ^  ^
   equal    all equal              equal

so 2 equal and 1 all equal

[3,5,6,5,5,7,6,6,8,7,7,7,3,4,2,4,4,3]     => [1, 3]
[3,3,3,4,4,4,5,5,5,6,6,6,5,4,3]           => [4, 0]
[3,4,5,6,7,8,9,8,7,6,5,4,3,2,1]           => [0, 0]

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

PD: Apologies for my English.

Octave, 60 52 50 bytes

@(x)sum(sum(~diff(sort(reshape(x,3,[]))))'==[2 1])

Try it online!

Saved 8 bytes thanks to Luis!

Explanation:

Reshapes the input into a matrix with 3 rows, and the appropriate amount of columns. It then sorts each of the columns, and calculates the difference between the elements on different rows. This gives a matrix with two rows, where identical numbers will have a zero, and different numbers will have a positive number. This is negated, so that all equal elements are 1, and all unequal are 0. We then sum each of those columns, giving us one of the three alternatives: 0 = All elements are unequal, 1 = Two elements are equal and 2 = All elements are equal. We then check how many are >1, and how many are exactly ==1.


How many balloons do I need in each corner? You have a square board with a bunch of items laid out on it in one of a \$3 \times 3\$ grid of cells and you want to lift it up using balloons, but you can only attach balloons to the corners of the board. Your task is to determine the minimum number of balloons in each corner to make sure the board won't tip over in flight, but can still lift all its contents.

"Physics" Model

Each balloon can lift 0.25kg (these are very strong balloons)
The board itself weighs 1kg, so you would need 1 balloon in each corner to lift an empty board
Items in each corner cell only exert force on their respective corners (i.e. 4 balloons are needed in the corresponding corner per kg)
Items on each edge cell split their force evenly between their neighboring corners (i.e. 2 balloons on each of the two corresponding corners per kg)
Items in the center cell split their force evenly across all corners (i.e. 1 balloon is needed in each corner per kg)

Example Test Cases

1

Input:
0 0 0
0 0 0
0 0 0

Output:
1 1
1 1

2

Input:
1 2 1
2 4 2
1 2 1

Output:
17 17
17 17

3

Input:
5 0 0
0 0 2
0 1 0

Output:
21 5
 3 7

4

Input:
12  9 35
 1 32  2
 4  6 18

Output:
101 195
 63 121

5

Input:
9999 9999 9999
9999 9999 9999
9999 9999 9999

Output:
89992 89992
89992 89992

6

Input:
9999    2 9001
   0 9999 9999
9999  999 9999

Output:
50000 66006
51994 71992

Rules and Assumptions

You may assume each cell is filled with a whole number between \$0\$ and \$9999\$ kg weight worth of items
Use any convenient format for I/O
Shortest code wins!

Jelly, 14 bytes

3Ḷ×þ`ZU$Ƭ×µ§§‘

Try it online!

Takes input as a 3x3 matrix and outputs a list going clockwise starting from the bottom-right.

Explanation

3Ḷ×þ`ZU$Ƭ×µ§§‘     Main Link
3Ḷ                 [0, 1, 2]
  ×þ`              outer product by multiplication with itself ([0, 0, 0], [0, 1, 2], [0, 2, 4])
        Ƭ          (include the original, plus) rotate clockwise until results are no longer unique (4 results total)
     ZU$           zip and upend (clockwise rotation)
         ×         vectorized multiply with original (gets the workload distributions to each balloon)
           §§      sum results for each balloon (vectorized-sum rows in the matrix; sum the results)
              ‘    increment


Calculating BPM with inputs Program the shortest code that will calculate the average BPM (Beats per Minute) using 8 data points of time passed. This is my first post, and I haven't seen a question similar to this. Since I am a fan of rhythm games, it would be nice to have a small handy tool to calculate BPM using your own keyboard and your own sense of rhythm (if you have one...)
Challenge

All inputs must be singular. (i.e. Only pressing "enter" as "input")
Your program must take at least 9 inputs. (To create 8 data points of time passed.)
Your program should output the BPM of the keypresses rounded at 2 decimal points. (i.e. 178.35)
Timing starts at first input. Not start of program

This is code-golf, so the shortest answer wins.
Example Input and Output
Provide at least one example input and output. Make sure they match your own description of what the input should look like.
Input:
> [Enter-Key]
# User waits 1 second
...  7 more inputs
> [Enter-Key]

Output:
> 60

Current winner is KarlKastor at 22 Bytes using Pyth
Even though the winner was using Pyth, the Matlab answer was a notable answer.

MATLAB/Octave, 58 56 55  bytes
Thanks @LuisMendo for -1 byte!
input('');tic;for k=1:7;input('');end;fix(48e3/toc)/100

You have to press enter 9 times. (Also works in Octave.)
Here you see it in action, left MATLAB, right Octave:


Hard Code Golf: Create a Chatroom Cue Storyline:  It is the early 21st century, and most things have become a thing of the past.  You and your fellow code-golf-eteers, however, are on a quest to reenact the 1990s.  As a part of this challenge, you must recreate a minimalistic chatroom.

The Goal:  To create a chatroom with as few bytes as possible.  The program(s) that you write shall function as a simple server, which serves a webpage, which allows users to post text onto the screen.

The Actual Goal:  To actually host a working chatroom from your own computer.  You don't have to do this, but it is a lot more fun this way.

Requirements:

Users should be able to give themselves a username that lasts for the session
Users should be able to repeatedly type and submit text, which will be displayed to other users
Each user should be able to see the text that is submitted by all users, along with the usernames of the submitters, and the information should be displayed in chronological order
The page should also display the number of people online and a list of their usernames
Your chatroom should be accessible to anyone on the internet who knows where to find it (such as knowing the IP address).
It should function in modern web browsers.

All else is up to you!

Submissions:

Should include the source code, or a link to the source code
Should include screenshots of the functional chatroom
Should include the total size, in bytes, of all of the programs/files that you have written that are required to make it work.

This challenge has been in the sandbox for a while now, so hopefully all of the kinks have been worked out.

PHP + JQuery + HTML + CSS, 1535 bytes

This is a submission leaning more towards what the OP deemed as 'the actual goal'. That is, a fully functional chat server, which may be hosted on just about any web server anywhere.

Functionality includes:

Notifications when users enter or leave the chat room.
Notifications when users change their alias.
Real time polling for new messages, without generating excess server traffic, or server load.
Layout and usability strongly resembling existing chat clients, such as X-Chat.

To being a session, enter an alias in the appropriate box, and press Tab or Enter to submit. If the alias is already in use, you will be notified. Sending messages is also done via Enter.

For your convenience, an archive of all files may be found here: chat.zip (choose Download from the File menu). To install, unpack to a web directory on any server running PHP 5.4 or higher.

Caveats:

IE 8 or lower will spin into an infinite loop while polling, because for some reason unknown to humanity, all Ajax requests are cached by default. It also prevents you from sending the same message twice, and updating the user list properly. This could be fixed by adding cache:false to every Ajax request.
In all version of IE, messages will not be sent by pressing Enter, because the change event is not triggered (pressing Tab, however, does work). This could be fixed by adding an onkeypress handler, checking if the key was Enter, and then calling $(v).blur().focus().

In short, IE is not supported.

Client

Positioning of elements could be a bit more robust, but it should look alright with a minimum window size of about ~800x600.

chat.htm (190 bytes)

<link rel=stylesheet href=c.css>
<select id=u multiple></select>

<input id=n onchange=u()><input id=v onchange=s()>

c.css (136 bytes)

i{color:#999}
#u{float:right;height:100%;width:200px;margin-left:10px}
#o{border:1px solid #999;height:93%;overflow-y:scroll}
#v{width:54%}

c.js (435 bytes)

var l
(function p(){
  $.ajax({url:'p.php',data:{n:$('#n').val()},success:function(d){
    $('#o').html(d).scrollTop(1e4);$('#u').load('n.php');
  },complete:p,timeout:2e4})
})()
function s(){
  $.get('s.php',{n:$(n).val(),v:$(v).val()})
  $(v).val('')
}
function u(){
  $.get('u.php',{l:i=l,n:l=$(n).val()}).fail(function(){
    alert("This name is already in use!")
    $(n).val(l=i)
  })
}
$(window).on('unload',function(){$.ajax({url:'l.php',data:{l:l},async:false})})

Server

I apologize for the server being broken up into so many tiny chunks. The alternative would be to use an adequate message protocol (via JSON encode/decode), or having a large if ... elseif ... according to which post variables are present. Making separate scripts, an just requesting from the one you need is a lot shorter, and perhaps simpler than both.

o.php (119 bytes) Opens as connection to the 'database'

<?$m=array_slice(unserialize(file_get_contents(m)),-300);
$u=unserialize(file_get_contents(u));$t=time();extract($_GET);

c.php (57 bytes) Commits changes to the 'database'

<?foreach([u,m]as$c)file_put_contents($c,serialize($$c));

p.php (151 bytes) Polls for new messages

<?for($t=time();@filemtime(m)<$t;usleep(1e3))clearstatcache();include('o.php');
foreach($m as$v)if($n&&$v[0]>=$u[$n])echo@date("[H:i]",$v[0])."$v[1]\n";

s.php (62 bytes) Send a message to the server

<?include('o.php');$m[]=[$t,"$n: $v"];include('c.php');

u.php (222 bytes) User registration or alias change

<?include('o.php');if(!trim($n)||$u[$n])exit(header('HTTP/1.1 418'));
$m[]=[$t,$u[$l]?
"$l is now known as $n.":
"$n has entered the chat."];
$u[$n]=$u[$l]?:$t;unset($u[$l]);include('c.php');

n.php (65 bytes) Retrieves the list of user names

<?include('o.php');foreach($u as$k=>$v)echo"<option>$k</option>";

l.php (98 bytes) User has left (closed their browser)

<?include('o.php');$m[]=[$t,"$l has left the chat."];
unset($u[$l]);include('c.php');


Let's draw the Triforce The Triforce is a fictional artifact in The Legend of Zelda, made of three identical-looking equilateral triangles representing power, wisdom and courage. Several games in the saga include an animation when the three parts finally join together.

The purpose of this challenge is to draw a single 2D frame of such a simplified animation, with a given width for the triangles and a given spacing between the parts.

Input

The input consists of two integers: a width \$w\ge1\$ and a spacing value \$s\ge0\$.

Output

The frame has to be drawn according to the following specifications:

         /\
        /  \____________ this part is horizontally centered
       /    \
      /______\
                    \___ s empty lines
                    /
   /\          /\
  /  \        /  \______ w+1 backslashes
 /    \      /    \
/______\    /______\
                \_______ 2w underscores
        |__|
          \_____________ 2s spaces

In the above example, we have \$w=3\$ and \$s=2\$.

More examples

\$w=1\$, \$s=0\$:

   /\
  /__\
 /\  /\
/__\/__\

\$w=2\$, \$s=0\$:

     /\
    /  \
   /____\
  /\    /\
 /  \  /  \
/____\/____\

\$w=3\$, \$s=3\$:

          /\
         /  \
        /    \
       /______\

   /\            /\
  /  \          /  \
 /    \        /    \
/______\      /______\

\$w=4\$, \$s=1\$:

          /\
         /  \
        /    \
       /      \
      /________\

    /\          /\
   /  \        /  \
  /    \      /    \
 /      \    /      \
/________\  /________\

Rules

Trailing spaces on each line are optional.
Extra leading spaces on each line are not allowed.
You may output a single extra leading newline and/or a single extra trailing newline.
This is code-golf.


Excel, 48 bytes

Hooray! Finally something Excel is actually good at.

=COUNT(VALUE(ROW(1:12)&"/"&A1/ROW(1:12)&"/"&A1))

Takes input from A1 in the form of an integer 1-99 representing the year, and outputs to wherever you enter this formula. It's an array formula, so use Ctrl-Shift-Enter instead of Enter to enter it.

This takes advantage of the fact that COUNT ignores errors, so any errors that are caused by either the month not dividing the year (leading Excel to parse something like 2/12.5/25 or by the date not being valid, like 2/29/58, are just silently ignored.


Why was 6 afraid of 7? Why was 6 afraid of 7? Because 7 8 9!

Given a string apply the following transformations:

If there is a 6 next to a 7 remove the 6 (6 is afraid of 7)
If the sequence "789" appears remove the 8 and the 9 (7 ate 9)

(If I'm not mistaken it doesn't matter what order you do the transformations in)

Keep applying these transformations until you can no longer.

Example:

78966

First we see "789", so the string becomes "766". Then we see "76", so we take out the 6, and the string becomes "76". Then we see "76" again, so we are left with "7".

Test Cases:

987 => 987 (Not in the right order. Does nothing.)
6 7 => 6 7 (The whitespace acts as a buffer between 6 and 7. Nothing happens)
676 => 7
7896789 => 77
7689 => 7
abcd => abcd

Retina, 12
Translation of the sed answer:
6*7(6|89)*
7

Try it online


Remove a letter to make a palindrome Problem
Let's say that a word is almost a palindrome if it is possible to remove one of its letters so that the word becomes a palindrome. Your task is to write a program that for a given word determines which letter to remove to get a palindrome.
The shortest code to do this in any programming language wins.
Input
Input consists of a word of uppercase letters from 2 to 1000 characters long.
Output
Output the 1-indexed position (leftmost letter has position 1, the next one has position 2 and so on) of the letter which should be removed. If there are possible choices that lead to the palindrome, output any of those positions. Note that you are required to remove a letter even if the given word is already a palindrome. If the given word is not almost an palindrome, output -1.

Example
The input:
racercar

might produce the output:
5

because removing the 5th letter produces racecar, which is a palindrome.
Also, the input
racecar

can still produce the output
4

because removing the 4th letter to produce raccar is still a palindrome.

Not-PHP Python (73):

[a[:g]+a[g+1:]==(a[:g]+a[g+1:])[::-1] for g in range(len(a))].index(1)

Where a is the string you want to check. This, however, throws an error if you can't turn it in an palindrome. Instead, you could use

try:print [a[:g]+a[g+1:]==(a[:g]+a[g+1:])[::-1] for g in range(len(a))].index(True)
except ValueError:print -1

EDIT: No, wait, it does work!

try: eval("<?php $line = fgets(STDIN); ?>")
except: print [a[:g]+a[g+1:]==(a[:g]+a[g+1:])[::-1] for g in range(len(a))].index(1)

Thanks, this does indeed raise the php-contents of this script by about 25% (that's what you want, right?)


Printing a "Hello World" one-liner in bourne shell without directly using white space char I'm currently trying to solve a tricky/silly challenge and i've come to a dead end.

The challenge is basically to form a one-liner /bin/sh compatible command line
which essentially outputs "Hello World" without directly typing White space or Tab characters in the command itself.

for example something like -

echo Hello World

would be invalid since we used white space twice in the command line.

Any ideas?

One which works in dash, so I suppose it is sh compatible;

IFS=@;command=echo@Hello@World;$command


Euro coins and notes As the majority of nations using the Euro have the  , as the decimal separator, you must use it also.
The task is to output all the values of the Euro coins and notes in ascending order. You must also put the trailing ,00 on the integer values.
0,01 0,02 0,05 0,10 0,20 0,50 1,00 2,00 5,00 10,00 20,00 50,00 100,00 200,00 500,00
I accept both output to stdout or a function returning an array/list. If output is to stdout, the acceptable separators between values are: space, tab, or newline.
There will be no accepted answer, unless I see some one I find very creative.
code-golf, so I want to know shortest answer by language.
Update:
Leading 0 zeros are not acceptable. Sorry, I should make it clear before.
Update 2:
It is also acceptable a function returning a string.


Coffee Machine Machine You left your computer for too long, and it went to sleep. Wake it up again by printing the following coffee maker.

________._________
|      | \   -   /
|  ||  |  \  -  /
|  ||  |___\___/
|  ||  |     X
|      |    ___
|      |   / - \
|______|  /  -  \
| ____ | /_______\
||7:30||__________
||____|           |
|_________________|

Reference image I used.

Specs

Any input must be included in the byte total.
Leading newlines and trailing whitespace is allowed.
Shortest code in bytes wins.


Fast inverse square root Inspired by http://meta.codegolf.stackexchange.com/questions/547/write-a-code-golf-problem-in-which-script-languages-are-at-a-major-disadvantage question on meta, I've decided to make a question which could be problematic for scripting languages.

The goal is to calculate fast inverse square root, just like it was done in Quake III Arena. You will get the floating point number as first argument after program name and you should implement it. Simply doing ** -0.5 is disallowed as it doesn't implement the algorithm.

Your program will be called like this. The 12.34 could be other value.

$ interpreter program 12.34 # for interpreted languages
$ ./a.out 12.34 # for compiled languages

For comparison, this is original Quake III Arena implementation.

float Q_rsqrt( float number )
{
        long i;
        float x2, y;
        const float threehalfs = 1.5F;

        x2 = number * 0.5F;
        y = number;
        i = * ( long * ) &y;                       // evil floating point bit level hacking
        i = 0x5f3759df - ( i >> 1 );               // what the heck?
        y = * ( float * ) &i;
        y = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration
//      y = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed

        return y;
}

You have to do just one iteration because the second was commented out.

Winning condition: Shortest code.

Jelly, 41 bytes

l2Ḟ©.*×+®µ23 .*×“9®ġ’_Hµ‘_Ḟ×Ḟ2*$$µ²×³3_×H

Try it online!

I know this challenge was designed in the hope that golfing languages would have a hard time. In a way, they do; Jelly doesn't have any primitives for looking at the representation of a floating point number in memory. However, it's still possible to solve the challenge via working out "manually" what the representation would look like using the basic definitions of floating point arithmetic, and in fact there's some amount of mathematical interest in doing things "the hard way". Jelly's so much terser than (say) C, that the fact it has to do more work doesn't prevent the program being considerably shorter.

Explanation

The input is a floating-point number, as a number.
In order to run the fast inverse square root algorithm, we need to find how it would be represented in memory.
Jelly doesn't have a way to do that by looking at the bit pattern, but we can do it arithmetically.

First, note that the input must be positive (or its inverse square root would be undefined). As such, it's laid out in memory as follows, from most to least significant:

A zero bit (the sign bit, zero means nonnegative so this will always be zero);
The exponent (dividing the number by 2 to the power of the exponent scales it into the range 1 to 2), represented in 8 bits as its value minus 127;
The mantissa (the result of the above division), represented in 23 bits via subtracting 1, then multiplying by 223.

The results of each of these calculations can be represented directly in Jelly. As such, we could generate the same output as C's convert-float-to-int memory hack does like this:

Calculate the exponent
Calculate the mantissa
Take ((exponent + 127) × 223) + (mantissa × 223 - 1)

However, the last expression shown here simplifies to the following rather simpler form:

223 × (exponent + mantissa + 126)
alternatively, 8388608 × (exponent + mantissa) + 1056964608 (the result of multiplying the above out)

Let's call the exponent + mantissa of the input floating point number em for short.
(The exponent + mantissa of a floating point number uniquely defines it.)
In other words, after the // evil floating point bit level hacking comment, the C program is currently working with i = 8388608 × em + 1056964608.

The next steps in the C program are to halve i, and subtract it from 0x5f3759df (which, in decimal, is 1597463007).
i is (8388608 × em + 1056964608); halving it gives (4194304 × em + 528482304); the subtraction gives (1068980703 - 4194304 × em).

Then, C convert this number back to a floating point number y. Let's call the exponent + mantissa of y em'.
What the C program is therefore effectively doing in the floating point representational hacking is solving the following equation:

(1068980703 - 4194304 × em) = (8388608 × em' + 1056964608), which simplifies to:
12016095 = 4194304 × em + 8388608 × em'
em' = (12016095 - 4194304 × em) ÷ 8388608 = (12016095 × 2-23) - em / 2

Now, to convert this into Jelly. We have a nice arithmetic definition of em and of em', so we can translate it directly. First, here's how to calculate em:

l2Ḟ©.*×+®
l2                 Logarithm of the input, base 2
  Ḟ                Round down to the integer below (produces the exponent)
   ©               Store the exponent in a variable
    .*             Take (½ to the power of the exponent)
      ×            Multiply by {the original value, by default}
       +®          Add the value of the variable (i.e. the exponent)

The original value multiplied by ½ to the power of the exponent is equal to the original value divided by 2 to the power of the exponent, i.e. the mantissa, so this is em.

Getting em' is very straightforward from here, if we want it. However, we're going to need to convert the exponent+mantissa format back into a floating point number.
This can be done unambiguously (the exponent's always an integer, the mantissa runs from 1 inclusive to 2 exclusive).
However, to extract the exponent, we're going to want to floor and subtract 1. As such, it's actually shorter to generate em' -1.

em' = (12016095 × 2-23) - em / 2, so
em'-1 = (3627487 × 2-23) - em / 2

We can encode this formula in Jelly directly:

µ23 .*×“9®ġ’_H
µ                  set this point as the new default for missing arguments
 23                restart with 23
    .*             ½ to the power of that (i.e. 2 to the power -23)
      ×            times
       “9®ġ’       3627487 (compressed representation)
            _H     minus half {the value as of the last µ command}

Incidentally, we need the space because 23. is a single token in Jelly (which evaluates to 23½).

The next step is to convert from em'-1 to an actual floating point number y. We can extract the exponent using Ḟ; then the mantissa is em'-1 + 1 - the exponent.
To produce the floating point number, we want to calculate mantissa × 2exponent:

µ‘_Ḟ×Ḟ2*$$
µ                  set this point as the new default for missing arguments
 ‘                 increment (producing em'-1 + 1)
  _Ḟ               subtract the exponent (producing the mantissa)
    ×              multiply by
     Ḟ2*           2 to the power of the exponent
        $$         parse the previous three links as a group

Finally, we just need to handle the line marked // 1st iteration.
This is just regular arithmetic, so encodes into Jelly really easily.
The formula is:

y × (1.5 - (x2 × y²)), where x2 is half the original input; this is shorter to express as
y ÷ 2 × (3 - (x × y²)), where x is the original input.

And here's how it looks in Jelly:

µ²×³3_×H
µ                  set this point as the new default for missing arguments
 ²                 square
  ×³               multiply (×) by the original input (³)
    3_             subtract (_) from 3
      ×H           multiply by half {the value as of the last µ command}

Verification

Running this program on the input 2 produces the output 0.7069300386983334. This is the same value (allowing for differences in the float-to-string conversion) as produced by this VBA answer, and not equal to the mathematically correct value for 2-0.5.


How on earth did llhuii output the Evil Numbers in 42 bytes of Python? This is a tips question for golfing in Python concerning the Evil Numbers question on Anarchy Golf.

An number is evil if its binary expansion has an even number of 1's. The challenge is to print the first 400 evil numbers 0,3,5,...,795,797,798, one per line.

The Python 2 submissions are led by llhuii with a 42-byte solution. The next best is 46 bytes by mitchs, followed by five 47-byte submissions. It seems llhuii has found something truly magical that has eluded many strong Python golfers for over 2 years. Saving 4 or 5 bytes is huge for such a short golf.

I'm still at 47 bytes. I'm hoping we can crack this puzzle as a community. If we get an answer jointly, I'd submit it under the names of everyone who contributed. An answer to this question can be a piece of code or a new idea or a piece of analysis. If you are llhuii, please don't spoil it for us yet.

Though submissions are not revealed because this problem is Endless, we're given some leads. The winning submission took 0.1699 seconds to run, much longer than any other, suggesting an inefficient method. From the byte statistics, of the 42 characters, 23 are alphanumeric [0-9A-Za-z] and 19 are ASCII symbols. This means there is no whitespace in llhuii's solution.

You can test your code on the problem page, choosing Python from the language dropdown or uploading a .py file. Note that:

Python 2.7 is used
Your code must be a full program that prints
There's no input for this problem, like kolmogorov-complexity
Your program just has to print the 400 values as given, even if it would break on larger values
Programs have 2 seconds to run
Programs may terminate with error
You may use exec; the "exec is denied" refers to shell exec

This isn't the same solution as llhuii's, but it's also 42 bytes long.

n=0;exec'print n;n^=(n^n+2)%3/2;n+=2;'*400

Try it online!

Thanks to @JonathanFrech, we're now at 40 bytes.

n=0;exec'print n;n=n+2^(n^n+2)/2%3;'*400

Try it online!

There's another byte to be saved, for a total of 39.

n=0;exec'print n;n=n+2^-(n^n+2)%3;'*400

Try it online!


Indices of elements in an array in order from smallest to largest Task

Basically you have an array of random integers e.g.

I() = [1, 4, 3, 2, 5, 3, 2, 1]

and you have to create another array of the same length with the numbers 1 to the size of the array in place of the smallest to largest numbers respectively, e.g.

O() = [1, 7, 5, 3, 8, 6, 4, 2]

For duplicates, the first occurrence is taken as the smaller of the indices.

Test Cases:

Input:   I() = [1, 5, 3, 4, 5, 3, 2, 4]
Output:  O() = [1, 7, 3, 5, 8, 4, 2, 6]

Input:   I() = [1, 5, 3, 2, 5, 3, 2, 4, 6, 6, 5]
Output:  O() = [1, 7, 4, 2, 8, 5, 3, 6, 10, 11, 9]

Rules

It should work with array of any finite length
All integers are positive(greater than 0)
This is code-golf, so the submission with the least amount of bytes wins!

Haskell, 41 bytes

f l|z<-zip l[0..]=[sum[1|q<-z,p>=q]|p<-z]

Try it online!

Haskell doesn't have build-in sorting, so we have to roll up our sleeves. We pair each element with its index with z<-zip l[0..], then for each pair counts the number of pairs that are smaller or equal. This first compares the values, then tiebreaks by their index.


Print the alphabet four times The program must print the alphabet four times: first in the normal alphabetical order, second in the order of a qwerty keyboard, third in the order of a dvorak keyboard, and lastly in reverse alphabetical order. The output should resemble this:

abcdefghijklmnopqrstuvwxyz
qwertyuiopasdfghjklzxcvbnm
pyfgcrlaoeuidhtnsqjkxbmwvz
zyxwvutsrqponmlkjihgfedcba

The output is not case-sensitive, and you can add or omit newlines or spaces wherever you wish.

The catch: the program must be less than 104 characters, or, in other words, smaller than the length of the alphabet times four.

I will accept the answer with the shortest code, unless I see something really clever or interesting that I am more impressed with.

EDIT: I will accept the shortest answer on Wednesday, 4/27/2011.

EDIT2: And the winner is (as usual) Golfscript in 64 chars! Second place, which is behind by only three chars, is also in Golfscript, with 67 chars, followed by Bash in third place with 72 chars.

But there were a few others I wanted to mention, such as this one, which, depending on your definition, only used 52 "characters", and this one where he wrote it in a language he created.

There were a few people who broke an unwritten rule and did not qualify, but I will mention them just for their way of thinking without the box.

PHP, 99 bytes
As ISO 8859-1:
<?=base64_encode("i·yø!9%z)ª»-ºü1Ë:°z»rº*)jÇ_ä<\½¹æ§'àr¹Z¡ë¢vg²¨äÅ¹°¿<òÇî¶Êê¦æHâÞuÆÚ");

To reproduce reliably,
printf '<?=base64_encode("' >| 4times.php
printf abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba | base64 -d >> 4times.php
printf '");' >> 4times.php


¡ǝƃuǝןןɐɥɔ uʍop ǝpısdn Turn the characters abcdefghijklmnopqrstuvwxyz!?., upside down and don't modify the other characters. Then, reverse the text to achieve the upside down affect. If text is already upside down, turn it right side up. Don't modify capitals.

Use this as a reference:

abcdefghijklmnopqrstuvwxyz!?.,
ɐqɔpǝɟƃɥıɾʞןɯuodbɹsʇnʌʍxʎz¡¿˙'

Rules

Newlines must be supported
You only have to convert the above character set.
Don't forget you need to reverse the characters.
This question is symmetrical unlike Small Caps Converter.

Test cases

42 is the meaning of life -> ǝɟıן ɟo ƃuıuɐǝɯ ǝɥʇ sı 24
halp why is my keyboard typing upside down??? :( -> (: ¿¿¿uʍop ǝpısdn ƃuıdʎʇ pɹɐoqʎǝʞ ʎɯ sı ʎɥʍ dןɐɥ
lol -> ןoן
uoɥʇʎpʎzɐɹc -> ɔrazydython

Look at my username!

Ruby, 78 bytes
I need to use an actual byte counter more often
->s{s.reverse.tr'a-z!?.,',"ɐqɔpǝɟƃɥıɾʞןɯuodbɹsʇnʌʍxʎz¡¿˙'"}

Try it online


Golf A Parentheses Matching Algorithm You will be given a string s. It is guaranteed that the string has equal and at least one [s and ]s. It is also guaranteed that the brackets are balanced. The string can also have other characters.
The objective is to output/return a list of tuples or a list of lists containing indices of each [ and ] pair.
note: The string is zero-indexed.
Example:
!^45sdfd[hello world[[djfut]%%357]sr[jf]s][srtdg][] should return
[(8, 41), (20, 33), (21, 27), (36, 39), (42, 48), (49, 50)] or something equivalent to this. Tuples are not necessary. Lists can also be used.
Test cases:
input:[[asdf][][td([)ty54g% ]hg[[f]u][f[[jhg][gfd]sdf]sdfs]ghd]fr43f]
output:[(0, 62),(1, 6), (7, 8), (9, 56), (13, 22), (25, 30), (26, 28), (31, 52), (33, 47), (34, 38), (39, 43)]
input:[[][][][]][[][][][[[[(]]]]]))
output:[(0, 9), (1, 2), (3, 4), (5, 6), (7, 8), (10,26),(11, 12), (13, 14), (15, 16), (17, 25), (18, 24), (19, 23), (20, 22)]
input:[][][[]]
output:[(0, 1), (2, 3), (4, 7), (5, 6)]
input:[[[[[asd]as]sd]df]fgf][][]
output:[(0, 21), (1, 17), (2, 14), (3, 11), (4, 8), (22, 23), (24, 25)]
input:[]
output:[(0,1)]
input:[[(])]
output:[(0, 5), (1, 3)]

This is code-golf, so the shortest code in bytes for each programming language wins.


Remove character at specified index (heavily inspired by Element of string at specified index)

Given a string s and an integer n representing an index in s, output s with the character at the n-th position removed.

0-indexing and 1-indexing are allowed.

For 0-indexing, n will be non-negative and less than the length of s.
For 1-indexing, n will be positive and less than or equal to the length of s.

s will consist of printable ASCII characters only (\x20-\x7E, or   through ~).

Any reasonable input/output is permitted. Standard loopholes apply.

Testcases (0-indexed):

n s        output
0 "abcde"  "bcde"
1 "abcde"  "acde"
2 "a != b" "a = b"
3 "+-*/"   "+-*"
4 "1234.5" "12345"
3 "314151" "31451"

Testcases (1-indexed):

n s        output
1 "abcde"  "bcde"
2 "abcde"  "acde"
3 "a != b" "a = b"
4 "+-*/"   "+-*"
5 "1234.5" "12345"
4 "314151" "31451"

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


Consistent Overhead Byte Stuffing (COBS) I'm surprised this hasn't been posted before!

The Consistent Overhead Byte Stuffing (COBS) algorithm is used to delimit byte streams.

We choose a frame marker (we'll use 0x00) and wherever 0x00 occurs in the stream it is replaced with the number of bytes until the next 0x00 occurs (we'll call this a milestone). This reduces the range of values from 0..255 to 1..255, enabling 0x00 to unambiguously delimit frames in the stream.
At a milestone, if the next 255B does not contain 0x00 this exceeds the maximum milestone length - the algorithm must 'stall' at 255B and put another milestone. This is the 'consistent overhead'.
The first byte will be the first milestone, the final milestone will be the number of bytes until the frame marker.

Some examples from Wikipedia (best to read the article where they are coloured):

0x00 as frame marker

Unencoded data (hex)    Encoded with COBS (hex)
00                      01 01 00
00 00                   01 01 01 00
11 22 00 33             03 11 22 02 33 00
11 22 33 44             05 11 22 33 44 00
11 00 00 00             02 11 01 01 01 00
01 02 03 ... FD FE      FF 01 02 03 ... FD FE 00
00 01 02 ... FC FD FE   01 FF 01 02 ... FC FD FE 00
01 02 03 ... FD FE FF   FF 01 02 03 ... FD FE 02 FF 00
02 03 04 ... FE FF 00   FF 02 03 04 ... FE FF 01 01 00
03 04 05 ... FF 00 01   FE 03 04 05 ... FF 02 01 00

Challenge: to implement this in the shortest program.

Input is an unencoded byte stream/array, output is an encoded byte stream/array
Use any sort of binary standard input/output
The final frame marker is not necessary
The program can return an oversized array
A stream ending with 254 non-zero bytes does not require the trailing 0x00

Notes

The worst-case return length is numBytes + (numBytes / 254) + 1

Example

We have the byte array

[0] 0x01
[1] 0x02
[2] 0x00
[3] 0x03
[4] 0x04
[5] 0x05
[6] 0x00
[7] 0x06

For each 0x00 we need to state (in a milestone) where the next 0x00 would have been.

[0] 0x03   #Milestone. Refers to the original [2] - "The next 0x00 is in 3B"
[1] 0x01   #Original [0]
[2] 0x02   #Original [1]
[3] 0x04   #Milestone. Refers to the original [6] - "The next 0x00 is in 4B"
[4] 0x03   #
[5] 0x04   #
[6] 0x05   # Originals [3..5]
[7] 0x02   #Milestone. Refers to the end frame marker
[8] 0x06   #Original [7]
[9] 0x00   #Optional. End frame marker.


Significant Whitespace: Cops For the purpose of this challenge, we'll define whitespace as only linefeeds (0x0A) and spaces (0x20). Note that most languages and regex flavours consider many other characters as whitespace as well, both inside and outside the ASCII range so you might not be able to make use of the corresponding built-ins.

The Cops' Challenge

You should write a program or function in a language of your choice, which takes a string, consisting of ASCII (except NUL) characters, as input and outputs it with all whitespace removed. For example if you received the following input:

H e l l o,
 W o r l  d!

You should output

Hello,World!

Your submission will then be your source code with all whitespace removed (the same process as passing your solution as input to itself, although your solution may also contain characters outside the ASCII range). Your goal is to make it as hard as possible to figure out where whitespace needs to be inserted to recover a valid solution in your language of choice. Note that robbers may insert fewer whitespace than you removed, but not more. Also remember that robbers don't have to match your exact code, they just have to find any valid solution.

Your answer should contain the following:

The language (and version if necessary) in which you wrote your solution.
The byte count of your solution before removing whitespace.
Your solution with whitespace removed.

Your solution may be either a program or function, but not a snippet and you must not assume a REPL environment. You may take input via STDIN, command-line argument or function argument and output via STDOUT, function return value or function (out) parameter.

In the interest of fairness, there must be a freely available interpreter or compiler for your chosen language.

You must not use built-ins for hashing, encryption or random number generation (even if you seed the random number generator to a fixed value). Your solution must be able to process any string of 100 characters or less in under 10 seconds on a reasonable desktop machine.

If your answer has not been cracked within 7 days (168 hours), you may reveal your own solution at which point your answer is considered safe. As long as you don't reveal your solution, it may still be cracked by robbers, even if the 7 days have already passed. The shortest safe answer wins (measured before removing whitespace).

If your answer does get cracked, please indicate this in the header of your answer, along with a link to the corresponding robber's answer.

Go here for the robbers' part.

Uncracked Submissions

Haskell, 100 bytes, cracked by nimi

main=interact$iddoidlinesidwordsdoidoidoid=doiddoid<-dooiidoid<-dooiddoiddodoid

This is a full program and a dadaistic poem.

Code with withspace (Try it online!)
main=interact$id doid lines id words
doid oi d o id=do
 iddoid<-do oi id
 oid<-do o iddoid
 do d oid

Still looking quite poetic, if you ask me.
De-obfuscated
main = interact f
f s = do
 l <- lines s
 w <- words l
 id w

Explanation
The do-notation is only syntactic sugar, so f can equivalently be written as
f s = lines s >>= words >>= id

For lists the >>=-operator is defined as concatMap, so f becomes
f = concat . map id . concat . map words . lines

So given an input "a b\nc", lines splits the input at newlines ["a b","c"], words splits each line at white space yielding [["a","b"],["c"]] (as I realised only now this includes newlines, so lines actually isn't needed). Concatenating once gives ["a","b","c"], id is the identity function and as such has no effect and the final concatenation yields the string "abc".