¿xu ti te gismytermorna? (Is it a valid gismu?) (Literally: "Does this follow/realize the gismu-form?")

Premise

The language Lojban is a constructed language, meaning in part that all of its words have been created rather than allowed to develop naturally. The semantic base of Lojban are its gismu, or root words, which were synthesized by combining roots from widely spoken natural languages like Chinese, Hindi, and English. All gismu are 5 letters long and follow a certain strict form.

Information

For our purposes, the Lojban alphabet is:

abcdefgijklmnoprstuvxz

That is, the Roman alphabet without hqwy.

This alphabet can be divided into four categories:

Vowels aeiou
Sonorant consonants lmnr
Unvoiced consonants ptkfcsx. When voiced, these become respectively the...
Voiced consonants bdgvjz (No voiced consonant corresponds to x.)

To be a valid gismu, a 5-char-long string must:

Be in one of the consonant-vowel patterns CVCCV or CCVCV, where C represents a consonant, and V represents a vowel.
Follow consonant-matching rules.

Consonant-matching rules for CCVCV words:

The first two characters must constitute one of the following 48 pairs (source):

ml mr
pl pr
bl br
   tr                   tc ts
   dr                   dj dz
kl kr
gl gr
fl fr
vl vr
cl cr cm cn cp ct ck cf
      jm    jb jd jg jv
sl sr sm sn sp st sk sf
      zm    zb zd zg zv
xl xr

Note that this looks rather nicer when separated into voiced and unvoiced pairs. In particular, every voiced-voiced pair is valid iff the corresponding unvoiced-unvoiced pair is valid. This does not extend to pairs with a sonorant consonant; cl is valid but jl is not.

Consonant-matching rules for CVCCV words (source):

The third and fourth characters must follow the following rules:

  It is forbidden for both consonants to be the same [...]
  It is forbidden for one consonant to be voiced and the other unvoiced. The consonants “l”, “m”, “n”, and “r” are exempt from this
  restriction. As a result, “bf” is forbidden, and so is “sd”, but both
  “fl” and “vl”, and both “ls” and “lz”, are permitted.
  It is forbidden for both consonants to be drawn from the set “c”, “j”, “s”, “z”.
  The specific pairs “cx”, “kx”, “xc”, “xk”, and “mz” are forbidden.

Note that there are 179 possible pairs.

Challenge

Determine if the given string follows the gismu formation rules. This is code-golf, so the shortest solution in bytes wins.

Input: A string of length 5 from the Lojban alphabet.

Output: A truthy value if the string can be a gismu and a falsey value otherwise.

Test cases

Valid:

gismu
cfipu
ranxi
mupno
rimge
zosxa

Invalid:

ejram
xitot
dtpno
rcare
pxuja
cetvu

More test cases: this text file contains all valid gismu, one per line.

I don't really know Lojban, so I suspect the title translation is wrong. Help is appreciated.

Ruby, 302 252 bytes
c='[cjsztdpbfvkgxmnlr]'
v=c+'[aeiou]'
z=!1
n=/#{c+v+v}/=~(s=gets.chop)*2
(n==0||n==2)&&289.times{|k|q=[i=k%17,j=k/17].max
z||=(x=s[n,2])==c[j+1]+c[i+1]&&['UeUeJOJOJOJOETJ
:'[i].ord-69>>j&1-j/14>0,i!=j&&q>3&&(k%2<1||q>12)&&!'mzxcxkx'.index(x)][n/2]}
p z

A few more bytes could be saved as follows:
Initialize z to false using z=!c='[cjsztdpbfvkgxmnlr]'. This works but gives the warning warning: found = in conditional, should be ==.
Change from a program to a function (I left it as a program because according to the question, shortest "program" in bytes wins.)
Summary of changes from first post
Major overhaul of regex/matching part.
Constant 72 changed to 69 so that the lowest ASCII code in the magic string is 10 instead of 13. This enables a literal newline to be used in the golfed version instead of an escape sequence.
Magic string 'mzxcxkx' replaces arithmetic rules for the 5 prohibited characters in the CVCCV type table.
ungolfed version
added whitespace and changed newline in magic string to a \n
c='[cjsztdpbfvkgxmnlr]'                                   #c=consonants
v=c+'[aeiou]'                                             #v=consonant+vowel
z=!1                                                      #Set z to false (everything is truthy in Ruby except nil and false.)
n=/#{c+v+v}/=~(s=gets.chop)*2                             #Get input and duplicate it. do regex match, n becomes the index of the double consonant.
(n==0||n==2)&&                                            #If n==0 (ccvcv) or n==2 (cvccv)
   289.times{|k|                                          #iterate 17*17 times
     q=[i=k%17,j=k/17].max                                #generate row and column, find their maximum.
     z||=                                                 #OR z with the following expression:
     (x=s[n,2])==c[j+1]+c[i+1]&&                          #double consonant == the pair corresponding to j,i AND either
       ["UeUeJOJOJOJOETJ\n:"[i].ord-69>>j&1-j/14>0,       #this expression or
       i!=j&&q>3&&(k%2<1||q>12)&&!'mzxcxkx'.index(x)][n/2]#this expresson, depending on the value of n/2
   }
p z                                                       #print output

Explanation of matching
The two characters in the input string s[n,2]are compared with the character pair of the iterating loop. If they match and the consonant-vowel regex pattern is correct, the row and column values i,j are checked for validity. Careful ordering of the consonants helps here.
For CVCCV:
i!=j                        It is forbidden for both consonants to be the same
(k%2<1||q>12)               It is forbidden for one consonant to be voiced and the other unvoiced. The consonants “l”, “m”, “n”, and “r” are exempt from this restriction. As a result, “bf” is forbidden, and so is “sd”, but both “fl” and “vl”, and both “ls” and “lz”, are permitted.
q>3                         It is forbidden for both consonants to be drawn from the set “c”, “j”, “s”, “z”.
!'mzxcxkx'.index(x)         The specific pairs “cx”, “kx”, “xc”, “xk”, and “mz” are forbidden.

For CCVCV
A bitmap for each column of the table below is encoded into the magic string, from which 69 is subtracted. For all columns except the last two, only 6 bits are required. For the last two, the higher order bits need to be 1, so a negative number is generated (characters \n and :) in order to have leading 1's instead of leading zeroes. We don't want to include the last three rows of the table though, so instead of rightshift and ANDing by 1, we rightshift and AND by 1-j/14 which normally evaluates to 1, but evaluates to 0 for the last 3 rows.
The following program (with the same expressions as the submission) was used to generate the tables below (uncomment whichever if line is required for the table you want.
c='[cjsztdpbfvkgxmnlr]'
z=0
289.times{|k|
  q=[i=k%17,j=k/17].max
  r=c[j+1]+c[i+1]
  #if i!=j && q>3 && (k%2<1||q>12) && !'mzxcxkx'.index(r)
  #if "UeUeJOJOJOJOETJ\n:"[i].ord-69>>j&1-j/14>0
    print r,' '
    z+=1
  else
    print '   '
  end
  i==16&&puts
}
puts z

            ct    cp    cf    ck       cm cn cl cr
               jd    jb    jv    jg    jm jn jl jr
            st    sp    sf    sk    sx sm sn sl sr
               zd    zb    zv    zg    zm zn zl zr
tc    ts          tp    tf    tk    tx tm tn tl tr
   dj    dz          db    dv    dg    dm dn dl dr
pc    ps    pt          pf    pk    px pm pn pl pr
   bj    bz    bd          bv    bg    bm bn bl br
fc    fs    ft    fp          fk    fx fm fn fl fr
   vj    vz    vd    vb          vg    vm vn vl vr
kc    ks    kt    kp    kf             km kn kl kr
   gj    gz    gd    gb    gv          gm gn gl gr
      xs    xt    xp    xf             xm xn xl xr
mc mj ms    mt md mp mb mf mv mk mg mx    mn ml mr
nc nj ns nz nt nd np nb nf nv nk ng nx nm    nl nr
lc lj ls lz lt ld lp lb lf lv lk lg lx lm ln    lr
rc rj rs rz rt rd rp rb rf rv rk rg rx rm rn rl
179

            ct    cp    cf    ck       cm cn cl cr
               jd    jb    jv    jg    jm
            st    sp    sf    sk       sm sn sl sr
               zd    zb    zv    zg    zm
tc    ts                                        tr
   dj    dz                                     dr
                                             pl pr
                                             bl br
                                             fl fr
                                             vl vr
                                             kl kr
                                             gl gr
                                             xl xr
                                             ml mr

48


Make a simple word wrapper (Note: This is my first ever code golf question, but as far as I can tell, nobody else has done exactly this, so I should be good.)

Your task is to make a program or function that takes in a string s and an integer n, and returns or outputs that text wrapped into multiple lines. Each word must be wholly on a line; i.e. no words split in the middle. Each line can be no longer than n characters long, and you must fit as many words as possible on each line.

Example:

s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
n = 50

output:
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Sed eget erat lectus. Morbi mi mi, fringilla
sed suscipit ullamcorper, tristique at mauris.
Morbi non commodo nibh. Pellentesque habitant
morbi tristique senectus et netus et malesuada
fames ac turpis egestas. Sed at iaculis mauris.
Praesent a sem augue. Nulla lectus sapien, auctor
nec pharetra eu, tincidunt ac diam. Sed ligula
arcu, aliquam quis velit aliquam, dictum varius
erat.

Your output can be an array of strings or a single string with line breaks. Also, you can assume no words will be longer than n, so don't worry about dealing with weird cases.

Standard I/O rules apply, and standard loopholes are prohibited. Trailing spaces are allowed.

Since this is code-golf, the shortes solution in bytes wins.

Here is an example program in Python that would work.

Python 2, 26 bytes

from textwrap import*
fill

Try it online!

Meh... built-ins are boring... instead, have a nice 87-byte solution here:

s,n=input()
x=''
for i in s.split():c=n<len(x+i);exec'print x'*c;x=x*-~-c+i+' '
print x

Try it online!

Outputs trailing spaces.


Help Jason format his JSON Jason has a big JSON but it's unreadable, so he needs to prettify it.

Formatting Spec

The JSON has 4 different types:

Numbers; Just 0-9
Strings; Double quoted " strings escaped with \
Arrays; Delimited by [], with items separated by ,, items can be any of these types
Objects; Delimited by {}, format is key: value where key is a string and value is any of these types

Spacing

Arrays should have exactly one space after the commas between items
Objects should have have just one space between the key and the value, after the :

Indentation

Each nesting level is indented 2 more than the previous
Each object key/value pair is always on its own line. Objects are indented
An array is indented across multiple lines if it contains another array or object. Otherwise the array remains on one line

Rules

Built-ins which trivialize this task are not allowed.
As always standard loopholes are disallowed

Examples

[1,2,3]
[1, 2, 3]

{"a":1,"b":4}
{
  "a": 1,
  "b": 4
}

"foo"
"foo"

56
56

{"a":[{"b":1,"c":"foo"},{"d":[2,3,4,1], "a":["abc","def",{"d":{"f":[3,4]}}]}]}
{
  "a": [
    {
      "b": 1,
      "c": "foo"
    },
    {
      "d": [2, 3, 4, 1],
      "a": [
        "abc",
        "def",
        {
          "d": {
            "f": [3, 4]
          }
        }
      ]
    }
  ]
}

[2,["foo123 ' bar \" baz\\", [1,2,3]]]
[
  2,
  [
    "foo123 ' bar \" baz\\",
    [1, 2, 3]
  ]
]

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

[1,2,3,{"b":["{\"c\":[2,5,6]}",4,5]}]
[
  1,
  2,
  3,
  {
    "b": ["{\"c\":[2,5,6]}", 4, 5]
  }
]

JavaScript (ES6), 368 bytes

f=(s,r=[],i='',j=i+'  ',a=[])=>s<'['?([,,r[0]]=s.match(s<'0'?/("(?:\\.|[^"])*")(.*)/:/(\d+)(.*)/))[1]:s<'{'?(_=>{for(;s<']';s=r[0])a.push(f(s.slice(1),r,j));r[0]=s.slice(1)})()||/\n/.test(a)?`[
${j+a.join(`,
`+j)}
${i}]`:`[${a.join`, `}]`:(_=>{for(a=[];s<'}';s=r[0])a.push(f(s.slice(1),r,j)+': '+f(r[0].slice(1),r,j));r[0]=s.slice(1)})()||`{
${j+a.join(`,
`+j)}
${i}}`

Less golfed:

function j(s, r=[], i='') { // default to no indentation
    if (s < '0') { // string
        let a = s.match(/("(?:\\.|[^"])*")(.*)/);
        r[0] = a[2]; // pass the part after the string back to the caller
        return a[1];
    } else if (s < '[') { // number
        let a = s.match(/(\d+)(.*)/);
        r[0] = a[2]; // pass the part after the string back to the caller
        return a[1];
    } else if (s < '{') { // array
        let a = [];
        while (s < ']') { // until we see the end of the array
            s = s.slice(1);
            a.push(j(s, r, i + '  ')); // recurse with increased indentation
            s = r[0]; // retrieve the rest of the string
        }
        r[0] = s.slice(1); // pass the part after the string back to the caller
        if (/\n/.test(a.join())) { // array contained object
            return '[\n  ' + i + a.join(',\n  ' + i) + '\n' + i + ']';
        } else {
            return '[' + a.join(', ') + ']';
        }
    } else { // object
        let a = [];
        while (s < '}') { // until we see the end of the object
            s = s.slice(1);
            let n = j(s, r, i + '  ');
            s = r[0].slice(1);
            let v = j(s, r, i + '  ');
            a.push(n + ': ' + v);
            s = r[0]; // retrieve the rest of the string
        }
        r[0] = s.slice(1); // pass the part after the string back to the caller
        return '{\n  ' + i + a.join(',\n  ' + i) + '\n' + i + '}';
    }
}


Maximal Skittle Enjoyment You've been given a bag of Skittles.  Everybody knows that in order to appreciate the different flavors the most, you need to rotate between the flavors.

Basics:

You can only eat 1 skittle at a time
The order that you eat your skittles must be periodic.
Each period cannot contain a particular flavor more than once.
Your bag only has so many skittles.  You cannot eat more of a particular flavor of skittle than appears in your bag.
You want to eat as many skittles as you can (it may not always be possible)

Examples:

Lets say you start with 3 Red, 2 Blue, and 3 Green skittles:

R B G R B G R G       Invalid:  The last R must be followed by a B, not a G
R B G R B G R         Valid, but sub-optimal
R R R                 Valid, but sub-optimal
R G B R G B R G       Valid and optimal
G R B G R B G R       Also valid and optimal (there are multiple good solutions)

Input/Output

You are passed a non-empty list of positive integers for the color counts.  (The above example would be [3,2,3]).
You need to return a list containing valid and optimal ordering.
Instead of using colors, you will use the indices from input list.  (The last example output above would be [2,0,1,2,0,1,2,0]).
Your output may be 0-indexed or 1-indexed.  My examples will be 0-indexed

Test Cases

1                          0
4                          0 0 0 0
4 1                        0 0 0 0
3 1                        0 1 0                   or  0 0 0
5 2 2                      0 1 2 0 1 2 0
2 3 5                      2 1 0 2 1 0 2 1         or  1 2 0 1 2 0 1 2
2 4 5                      2 1 2 1 2 1 2 1 2
3 4 5                      2 1 0 2 1 0 2 1 0 2 1   or  1 2 0 1 2 0 1 2 0 1 2
1 1 1 1 1 6                5 0 1 2 3 4 5           (lots of other solutions)
1 1 1 1 1 8                5 5 5 5 5 5 5 5
2 4 6 8                    3 2 1 3 2 1 3 2 1 3 2 1 3 2

This is a code-golf, so make your solutions as short as possible in your favorite language!

JavaScript (ES6), 177 175 bytes

a=>a.map((n,i)=>[n,l=i]).sort((a,b)=>a[0]-b[0]).reduce((P,x,i,a)=>(v=a.reduce((p,c,j)=>j<i?p:p+Math.min(c[0],x[0]+1),0))>m?[...Array(m=v)].map((_,k)=>a[l-k%(l+1-i)][1]):P,m=0)

Formatted and commented

a => a                              // given an array a:
.map((n, i) => [n, l = i])          // map it to [value, index] arrays / set l = length - 1
.sort((a, b) => a[0] - b[0])        // sort it by values in ascending order
.reduce((P, x, i, a) =>             // for each reference entry x at position i:
  (v = a.reduce((p, c, j) =>        //   for each entry c at position j:
    j < i ?                         //     if c is before x:
      p                             //       keep the previous sum (which is 0)
    :                               //     else:
      p + Math.min(c[0], x[0] + 1), //       add minimum(value[j], value[i] + 1)
    0                               //   initialize the sum at 0
  )) > m ?                          //   if the new sum v is better than our current best m:
    [...Array(m = v)].map((_, k) => //     update m to v and update the result to an array
      a[l - k % (l + 1 - i)][1]     //     of length m filled with indices picked repeatedly
    )                               //     between i and l
  :                                 //   else:
    P,                              //     keep the previous result
  m = 0                             // start with best score m = 0
)                                   // the final result is returned by the outer reduce()

Used formula

Below is a table showing how the formula F(i, j) = minimum(value[j], value[i] + 1) is working, here with i = 0 and the input [ 5, 2, 2 ].

This formula can be interpreted as follows: for each Skittle type, we can select no more than the number of the least available type plus one.

 j | Sorted    | value[j] | F(0, j) | Selected        | Output
   | input     |          |         | Skittles        | (starting from bottom left)
---+-----------+----------+---------+-----------------+-----------------------------
 0 | 2 2       |     2    |    2    | [2] [2]         | \
 1 | 1 1       |     2    |    2    | [1] [1]         |  > 0 1 2 0 1 2 0
 2 | 0 0 0 0 0 |     5    |    3    | [0] [0] [0] 0 0 | /

Test cases

let f =

a=>a.map((n,i)=>[n,l=i]).sort((a,b)=>a[0]-b[0]).reduce((P,x,i,a)=>(v=a.reduce((p,c,j)=>j<i?p:p+Math.min(c[0],x[0]+1),0))>m?[...Array(m=v)].map((_,k)=>a[l-k%(l+1-i)][1]):P,m=0)

console.log(JSON.stringify(f([ 1                ]))); // 0
console.log(JSON.stringify(f([ 4                ]))); // 0 0 0 0
console.log(JSON.stringify(f([ 4, 1             ]))); // 0 0 0 0
console.log(JSON.stringify(f([ 3, 1             ]))); // 0 1 0
console.log(JSON.stringify(f([ 5, 2, 2          ]))); // 0 2 1 0 2 1 0
console.log(JSON.stringify(f([ 2, 3, 5          ]))); // 2 1 0 2 1 0 2 1
console.log(JSON.stringify(f([ 2, 4, 5          ]))); // 2 1 2 1 2 1 2 1 2
console.log(JSON.stringify(f([ 3, 4, 5          ]))); // 2 1 0 2 1 0 2 1 0 2 1
console.log(JSON.stringify(f([ 1, 1, 1, 1, 1, 6 ]))); // 5 4 3 2 1 0 5
console.log(JSON.stringify(f([ 1, 1, 1, 1, 1, 8 ]))); // 5 5 5 5 5 5 5 5
console.log(JSON.stringify(f([ 2, 4, 6, 8       ]))); // 3 2 1 3 2 1 3 2 1 3 2 1 3 2


Give me your tired, your poor, Your huddled masses yearning to breathe free A bronze plaque in the pedestal of the Statue of Liberty displays the poem "The New Colossus" by Emma Lazarus, part of which reads:

  Give me your tired, your poor,
  Your huddled masses yearning to breathe free,
  The wretched refuse of your teeming shore.
  Send these, the homeless, tempest-tost to me,
  I lift my lamp beside the golden door!

To simplify this section of the poem for this challenge, we'll make it all uppercase and replace the newlines with slashes (/), keeping commas and other punctuation as is:

GIVE ME YOUR TIRED, YOUR POOR,/YOUR HUDDLED MASSES YEARNING TO BREATHE FREE,/THE WRETCHED REFUSE OF YOUR TEEMING SHORE./SEND THESE, THE HOMELESS, TEMPEST-TOST TO ME,/I LIFT MY LAMP BESIDE THE GOLDEN DOOR!

We'll call this string S. It has md5 hash 8c66bbb9684f591c34751661ce9b5cea. You may optionally assume it has a trailing newline, in which case the md5 hash is 0928ff6581bc207d0938b193321f16e6.

Write a program or function that takes in a single string. When the string is S, output in order, one per line, the six phrases that describe the type of people the poem depicts Lady Liberty asking for:

TIRED
POOR
HUDDLED MASSES YEARNING TO BREATHE FREE
WRETCHED REFUSE OF YOUR TEEMING SHORE
HOMELESS
TEMPEST-TOST

(This precise string, optionally followed by a single trailing newline, must be your output for input S.)

For at least one input string that is not S, your output should be any string other than the six lines above. This could be as simple as outputting only TIRED if the input is only GIVE ME YOUR TIRED. This rule is to prevent pure hardcoding. Otherwise, when the input string is not S, your code may do anything.

This is essentially a constant-output challenge where you are given an input that is relatively close to the output. You could of course mostly ignore the input and hardcode the output, but it may be better to, say, strip out the substrings of the input needed for the output.

For reference, here are the zero-based indices and lengths of the six output lines in S:

13 5, 25 4, 36 39, 81 37, 136 8, 146 12

The shortest code in bytes wins.

Jelly, 19 bytes

Ẇ“©ØḌKAƑ⁶2ɼU’b8ȷ¤ịY

Try it online! or try it with some other text.

How?

Indexes into the list of all non-empty contiguous slices of the input string and joins with line feeds.

Ẇ“©ØḌKAƑ⁶2ɼU’b8ȷ¤ịY - Main link: s
                ¤   - nilad followed by link(s) as a nilad
 “©ØḌKAƑ⁶2ɼU’       - base 250 number, 27003436588466956354336
              8ȷ    - 8 * 1e3 = 8000
             b      - convert to base, [824,635,7086,6796,1544,2336]
                 ị  - index into
Ẇ                   - all non-empty contiguous slices of s
                  Y - join with line feeds

Previous code, 22 bytes:

“ÇŒȷœ%LRw⁹ƊƓɠ‘ṬœṗµḊm2Y

Partitions the input string, takes every second element and joins with line feeds. “ÇŒȷœ%LRw⁹ƊƓɠ‘ is a list of code page indexes, Ṭ makes a list of zeros with ones at those indexes, œṗ partitions the input at the truthy indexes of that list, Ḋ removes the first element, m2 takes every second element, and Y joins with line feeds.


Produce n n-squares of integers with rotating *'s in consecuitive corners The objective is to produce output of n squares (nxn) of random integers (0-9) with a moving * that rotates clockwise around the corners, starting from the top left. The squares should be side by side and separated by a single space.

If n = 0, the output should be empty.

Output for n=1:

*

Output for n=2:

*3 4*
14 07

Output for n=3:

*34 82* 291
453 224 924
145 158 57*

Output for n=4:

*153 135* 0154 0235
2352 5604 3602 2065
2245 6895 3561 7105
7225 5785 479* *662

Notice how the * rotates (around the corners of the square), from left to right, like this: top left, top right, bottom right, bottom left, top left, etc. (clockwise)

The shortest answer (measured in bytes) wins.

Dyalog APL, 57  bytes

Requires ⎕IO←0 which is default on many systems.
Assuming double-spacing is permitted, as per the OP's first example.
{A←⊃∘⍕¨?10⍴⍨3⍴⍵⋄A[(⍳⍵),¨⍵⍴2↑¨1⍵(⍵ ⍵)(1⍵)-1]←'*'⋄⍉⎕FMT A}

TryAPL online!
Non-competing 49-byte solution (Dyalog APL 16.0):
{⍉⎕FMT'*'@((⍳⍵),¨⍵⍴2↑¨1⍵(⍵ ⍵)(1⍵)-1)⊃∘⍕¨?10⍴⍨3⍴⍵}


How Persistent am I? Your Task:

Write a program or function that, when given a number, outputs its persistence.  The persistence of a number is the number of times you can add its digits before arriving at a one-digit number.  All one digit numbers have a persistence of 0.  Note that this is different from questions about finding the digital root, as those questions ask for the end result of this process, whereas this question wants the number of steps required to get there.

Input:

An integer.

Output:

The persistence of the inputted integer.

Examples:

1-->0 (1=1)
12-->1 (1+2=3)
99-->2  (9+9=18, 1+8=9)
9999-->2 (9+9+9+9=36, 3+6=9)

Scoring:

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

Python 2, 50 39 bytes

-10 thanks to @JonathanAllan

f=lambda x:x>9and-~f(sum(map(int,`x`)))

Try it online!


Bilibili AV/BV Code Conversion Background
Bilibili is a China-based video sharing platform, similar to Nico Nico Douga in Japan, and Youtube around the world.
Since the establishment, Bilibili had been using the AV code to reference a video. An AV code is a string of 3 or more characters, starting with av and followed by a natural number, like av82054919.
However, since 23 March 2020, Bilibili introduced a new referencing system called the BV code. This time, the code is a string of exactly 12 characters, starting with BV and followed by 10 alphanumerical characters, like BV1XJ41157tQ. Still, users can use both codes to reference a video, and there is a conversion algorithm between the two.
(For your information, the two examples reference the same video)
The algorithm
To convert from AV code to BV code:

Remove the av part of the AV code.
Do a bitwise XOR between the result in step 1 (as a number) and 177451812.
Add 8728348608 to the result in step 2.
Convert the result in step 3 to a 6-digit base-58 number with digits fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF in place of 0, 1, ..., 57 respectively. Here, 0, I, O, l are omitted to eliminate ambiguity. Assume the result is abcdef.
The BV code is then BV1db4a1c7ef.

To convert from BV code to AV code:

Remove the 1st to 3rd, the 6th, the 8th and the 10th characters. Assume the result is abcdef.
Rearrange the result in step 1 to cbdaef.
Treat the result in step 2 as a base-58 number with digits fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF in place of 0, 1, ..., 57 respectively. Convert this base-58 number into decimal.
Subtract 8728348608 from the result in step 3.
Do a bitwise XOR between the result in step 4 and 177451812.
The AV code is then av followed by the result in step 5.

Example
To convert av82054919 to BV code:

Removing av from the code results in 82054919.
\$82054919\text{ XOR }177451812=242727971\$
\$242727971+8728348608=8971076579\$
\$8971076579_{10} = (13,38,43,6,30,7)_{58}\$ → 1J5XtQ
Substituting: BV1[X][J]4[1]1[5]7[t][Q] → BV1XJ41157tQ

To convert BV1XJ41157tQ back to AV code:

Remove the bracketed numbers: [BV1]XJ[4]1[1]5[7]tQ → XJ15tQ
Rearranging the characters results in 1J5XtQ.
1J5XtQ → \$(13,38,43,6,30,7)_{58} = 8971076579_{10}\$
\$8971076579-8728348608=242727971\$
\$242727971\text{ XOR }177451812=82054919\$
Prepending av to the result, we have av82054919.

Challenge
Write two independent programs or functions, one receiving the AV code as input and outputting the corresponding BV code, and one receiving the BV code as input and outputting the corresponding AV code. Both the prefixes av and BV are case insensitive, you may choose either upper or lower case to accept or output. Each code should work even without the code from the other.
You may assume that the input for both programs must have a valid format, and the number in its corresponding AV code is between 1 and 2147483647 inclusive.
Test cases
AV code <-> BV code
av82054919 <-> BV1XJ41157tQ
av123456789 <-> BV1yn411L7tG
av1 <-> BV1xx411c7mQ
av2147483647 <-> BV1Fr4k1q7G1

You may check your results through this tool (not developed by me). Click the first button after entering the AV/BV code into the input, then the textbox will show the result.
Winning condition
The total length of the codes of the two programs (measured in bytes) will be your code length, and since this is a code-golf challenge, the submission with shortest code length for each language wins. No standard loopholes.

Python 2, 170 + 150 = 320 bytes

AV to BV, 180 179 173 170 bytes:

lambda s:"BV1{2}{4}4{5}1{3}7{1}{0}".format(*["fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF"[((int(s[2:])^177451812)+8728348608)/58**i%58]for i in range(6)])

Try it online!

BV to AV, 165 158 150 bytes:

s=input()
n=0
for i in 6,4,8,3,10,11:n=n*58+"fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF".find(s[i])
print"av"+`n-8728348608^177451812`

Try it online!


The Gray area of n-ary codes Write a program or function that takes a base n and a number x, and returns or outputs the n-ary Gray code of x.

Rules

n is an integer in the range 2 <= n <= 16.
x is an integer in the range 0 <= n < 2**32.
The inputted numbers can either be two integer arguments if you write a function, or two arguments to ARGV or a space separated pair to STDIN if you write a program.
The output should be a string, either returned or printed to STDOUT.
If n is 10 or more, use hex digits to represent digits with a value greater than 9. The case of the digits does not matter.
If the n-ary Gray code of x is zero, '0' must be printed or returned.
Code length is in bytes, and standard loopholes are not permitted.
You do not need to use the same algorithm as below, but if you use a different one, make sure it produces valid Gray codes.

Example

Example code adapted from Wikipedia:

>>> import string
>>>
>>> def nary_gray_code(base, num):
...     base_num = []
...     # Convert to num to base base
...     while num:
...         base_num.append(num % base)
...         num = num // base
...     # Convert base base number to base-ary Gray code
...     shift = 0
...     gray = []
...     for b in reversed(base_num):
...         gray.insert(0, (b + shift) % base)
...         shift += base - gray[0]
...     return "".join(string.hexdigits[i] for i in reversed(gray)) or "0"
...
>>> nary_gray_code(2, 100)
'1010110'
>>> nary_gray_code(2, 1)
'1'
>>> nary_gray_code(2, 0)
'0'
>>> nary_gray_code(10, 23)
'21'
>>> nary_gray_code(10, 100)
'190'
>>> nary_gray_code(3, 26)
'200'
>>> nary_gray_code(3, 27)
'1200'
>>> for i in range(2, 17):
...     print(i, nary_gray_code(i, 2**32 - 1))
...
2 10000000000000000000000000000000
3 122102120011102000122
4 3000000000000000
5 34020102231331
6 1401154214013
7 260241350125
8 34000000000
9 11762782617
10 4875571576
11 1824007509
12 92b627446
13 5b25a2c00
14 2ac96ab2b
15 197dde1a7
16 f0000000
>>>

Pyth, 20 bytes

Msme.H%dGu+G-HsGjHGY

This defines a function g which takes two integers as parameters. Take a look at this online demonstration: Pyth Compiler/Executor.

Explanation:

Msme.H%dGu+G-HsGjHGY
M                     def g(G, H): return _
                jHG      convert H to base G
         u      jHGY     reduce(lambda G, H: _, jHG, [])
          +G-HsG            G + [H - sum(G)]
  m                      map each number d to:
   e.H%dG                   hex-representation(d % G)[-1]
 s                       sum (join all digits)

This code is a little bit confusing. There are 4 function parameters in this code: two of them are called G and two of them are called H. The G in +G-HsG is different from the G in jHG or %dG.


Advent Challenge 7: Balance the storage carts! << Prev Next >>

After some careful analysis, Santa was able to determine the dock size ranges and get the presents into the correct transportation dock.

Now, he needs you to help him balance out the transportation carts and place the presents in them in the most balanced fashion.

Challenge

You will be given the size of (the base of) the transportation cart as (width, height) and a list of all of the presents' sizes as integers.

An arrangement of presents on the transportation cart will have a certain center of mass, which should be as close to the center as possible (in other words, you want to minimize the Euclidean Distance between the center of mass and (width / 2, height / 2). The center of mass can be calculated by the following formula.

Formula

Let {(x_1, y_1), (x_2, y_2), ..., (x_i, y_i)} be the coordinates of the centers of the presents (these coordinates may be half-numbers (so #.5) if the
size is even). Let s = {s_1, s_2, ..., s_i} be the sizes of the presents.

Then, the center of mass is at ((x_1 × s_1 + x_2 × s_2 + ... + x_i × s_i) / sum(s), (y_1 × s_1 + y_2 × s_2 + ... + y_i × s_i) / sum(s)).

Task

Given the dimensions of the transportation cart m × n and the sizes of the presents, determine the positions of the presents in the most balanced arrangement. Note that presents may not intersect; each present with size s is an s × s × s cube.

Formatting Specifications

You may give the output in any reasonable format; for example, the positions of the top-left corners of the presents, the centers, an m × n matrix of integers indicating what present covers each space, etc. If there are multiple valid answers, you may return just one (does not have to be deterministic) or you can return them all.

Test Cases

Input
Output (given as the `m × n` matrix as ASCII-art)
----
5 × 5, 2, 2, 2, 2
11022    00220
11022    11220
00000 or 11033
33044    04433
33044    04400
----
5 × 7, 1, 1, 1, 2, 2
1000022
0000022
0003000 (or others)
4400000
4400005
----
3 × 4, 3
1110
1110
1110
---
3 × 4, 2, 1
0110
0110
0020

Please feel free to correct me if my test cases are not correct.

Rules

Standard Loopholes Apply
This is a code-golf, so the shortest answer in bytes wins
No answer will be accepted
There will always be at least one solution to all of the inputs

Note: I drew inspiration for this challenge series from Advent Of Code. I have no affiliation with this site

You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge here.

Happy Golfing!

Python 3, 533 494 476 bytes

from numpy import*
def o(a,v,t=[],n=1):
 if len(v)<1:return[[sum((d-e)**2for d,e in zip([sum(a)/sum(r)for a in zip(*[[a*k for k in b]for a,b in zip(r,t)])],[-~a/2 for a in a.shape]))**.5,a]]
 s,k=v[0],[[]]
 for p,i,j,l in[[copy(a),i,j,(i-~s/2,j-~s/2)]for i in range(a.shape[0]-s+1)for j in range(a.shape[1]-s+1)if all(a[i:i+s,j:j+s]<1)]:p[i:i+s,j:j+s]=n;k+=o(p,v[1:],t+[l],n+1)
 return k
w=input()
q,r=w[0],w[1:]
print(min([a for a in o(zeros(q),r)if a],key=lambda a:a[0])[1])

Try it online!
I used the numpy library in Python.  It is a very popular Python library and it specializes matrix/multi-dimensional array manipulation.
Mine finds a different, but equally valid, solution.  I did double check my work and, when I tried to find all solutions, it did find the one presented in the question as well.
Basic methodology is to bruteforce it.  So, every possible present location is checked, then the one with the least distance between it's center of gravity and the center of the slay is returned (or at least one of the possible solutions).

Pseudo-Ungolfed Version
I figured providing the ungolfed version would help people understand the algorithm.  I have made marginal improvements since this version, but this should give you a jump start in understanding it:
import numpy as np

with open("test.txt","w") as fo:
    input = lambda: [[3,4], 2, 1]

    def bruteForce(array, size, number):
        for i in range(array.shape[0]-size+1):
            for j in range(array.shape[1]-size+1):
                if np.all(array[i:i+size,j:j+size] == 0):
                    temp = np.copy(array)
                    temp[i:i+size,j:j+size] = number
                    yield temp, (i+(size+1)/2,j+(size+1)/2)

    #y, x because of how numpy works
    #euclid = https://codegolf.stackexchange.com/a/70536/67929
    def recursiveCheck(array,presents,presentLocations=[],number=1,currentMin=[10000,[]]):
        global rest, size
        if (len(presents) == 0):
            centerI = sum(a*b[0] for a,b in zip(rest,presentLocations)) / sum(rest)
            centerJ = sum(a*b[1] for a,b in zip(rest,presentLocations)) / sum(rest)
            euclid = lambda a,b:sum((d-e)**2for d,e in zip(a,b))**.5
            centerDelta = euclid([centerI,centerJ],[(a+1)/2 for a in array.shape])
            if centerDelta <= currentMin[0]:
                currentMin[0] = centerDelta
                currentMin[1] = array
                fo.write(repr(array) + "\n")
                fo.write(repr(presentLocations) + "\n")
                fo.write(repr([centerI,centerJ]) + "\n")
                fo.write(repr(centerDelta) + "\n")
            return
        for potentialPresentArray, newPresentLocation in bruteForce(array,presents[0],number):
            recursiveCheck(potentialPresentArray,presents[1:],presentLocations+[newPresentLocation],number+1,currentMin)

    suMatrix = input()
    size = suMatrix[0]
    rest = suMatrix[1:]
    recursiveCheck(np.zeros(size),rest)

Credits
I used a response by CarpetPython to aide me in creating a euclidean distance calculation in a minimal amount of bytes.
Mr. Xcoder reduced it by 28 bytes.


Extract Local Maxima Given an array of positive integers, output an array of all the elements that are greater than or equal to the adjacent ones. Most elements will have two adjacent elements; the first and last element are special cases, as they only have one adjacent element.

You may assume that the array contains at least two elements.

Test cases:

Input               | Output
[4,2,6,12,4,5,4,3]  | [4,12,5]
[1,2]               | [2]
[1,2,3,2,1]         | [3]
[3,2,1,2,3]         | [3,3]
[4,4]               | [4,4]
[2,4,4,4,1]         | [4,4,4]
[2,3,3,4]           | [3,4]
[4,3,3,4]           | [4,4]

This is code-golf, shortest code wins!

Python, 54 bytes

f=lambda l,*p:l and l[:p<=l[:1]>=l[1:2]]+f(l[1:],l[0])

Try it online!

I/O is with tuples rather than lists.

Python, 57 bytes

f=lambda l,p=0:l and l[:[p]<=l[:1]>=l[1:2]]+f(l[1:],l[0])

Try it online!

Alt 57:

f=lambda l,p=0:l and l[l<[max(p,*l[:2])]:1]+f(l[1:],l[0])


Simulate a Minsky Register Machine (I) There are many formalisms, so while you may find other sources useful I hope to specify this clearly enough that they're not necessary.

A RM consists of a finite state machine and a finite number of named registers, each of which holds a non-negative integer. For ease of textual input this task requires that the states also be named.

There are three types of state: increment and decrement, which both reference a specific register; and terminate. An increment state increments its register and passes control to its one successor. A decrement state has two successors: if its register is non-zero then it decrements it and passes control to the first successor; otherwise (i.e. register is zero) it simply passes control to the second successor.

For "niceness" as a programming language, the terminate states take a hard-coded string to print (so you can indicate exceptional termination).

Input is from stdin. The input format consists of one line per state, followed by the initial register contents. The first line is the initial state. BNF for the state lines is:

line       ::= inc_line
             | dec_line
inc_line   ::= label ' : ' reg_name ' + ' state_name
dec_line   ::= label ' : ' reg_name ' - ' state_name ' ' state_name
state_name ::= label
             | '"' message '"'
label      ::= identifier
reg_name   ::= identifier

There is some flexibility in the definition of identifier and message. Your program must accept a non-empty alphanumeric string as an identifier, but it may accept more general strings if you prefer (e.g. if your language supports identifiers with underscores and that's easier for you to work with). Similarly, for message you must accept a non-empty string of alphanumerics and spaces, but you may accept more complex strings which allow escaped newlines and double-quote characters if you want.

The final line of input, which gives the initial register values, is a space-separated list of identifier=int assignments, which must be non-empty. It is not required that it initialise all registers named in the program: any which aren't initialised are assumed to be 0.

Your program should read the input and simulate the RM. When it reaches a terminate state it should emit the message, a newline, and then the values of all the registers (in any convenient, human-readable, format, and any order).

Note: formally the registers should hold unbounded integers. However, you may if you wish assume that no register's value will ever exceed 2^30.

Some simple examples

a+=b, a=0

s0 : a - s1 "Ok"
s1 : b + s0
a=3 b=4

Expected results:

Ok
a=0 b=7

b+=a, t=0

init : t - init d0
d0 : a - d1 a0
d1 : b + d2
d2 : t + d0
a0 : t - a1 "Ok"
a1 : a + a0
a=3 b=4

Expected results:

Ok
a=3 b=7 t=0

Test cases for trickier-to-parse machines

s0 : t - s0 s1
s1 : t + "t is 1"
t=17

Expected results:

t is 1
t=1

and

s0 : t - "t is nonzero" "t is zero"
t=1

Expected results:

t is nonzero
t=0

A more complicated example

Taken from the DailyWTF's Josephus problem code challenge. Input is n (number of soldiers) and k (advance) and output in r is the (zero-indexed) position of the person who survives.

init0 : k - init1 init3
init1 : r + init2
init2 : t + init0
init3 : t - init4 init5
init4 : k + init3
init5 : r - init6 "ERROR k is 0"
init6 : i + init7
init7 : n - loop0 "ERROR n is 0"
loop0 : n - loop1 "Ok"
loop1 : i + loop2
loop2 : k - loop3 loop5
loop3 : r + loop4
loop4 : t + loop2
loop5 : t - loop6 loop7
loop6 : k + loop5
loop7 : i - loop8 loopa
loop8 : r - loop9 loopc
loop9 : t + loop7
loopa : t - loopb loop7
loopb : i + loopa
loopc : t - loopd loopf
loopd : i + loope
loope : r + loopc
loopf : i + loop0
n=40 k=3

Expected results:

Ok
i=40 k=3 n=0 r=27 t=0

That program as a picture, for those who think visually and would find it helpful to grasp the syntax:

If you enjoyed this golf, have a look at the sequel.

Perl, 166

@p=<>;/=/,$_{$`}=$' for split$",pop@p;$o='\w+';(map{($r
,$o,$,,$b)=$'=~/".*?"|\S+/g if/^$o :/}@p),$_=$o=($_{$r}
+=','cmp$o)<0?do{$_{$r}=0;$b}:$,until/"/;say for eval,%_

Run with perl -M5.010 file.

It started wildly different, but I'm afraid it converged with the Ruby solution in many areas towards the end.  Seems like Ruby's advantage is "no sigils", and Perl's "better regex integration".

A bit of detail from the innards, if you don't read Perl:

@p=<>: read the whole machine description to @p
/=/,$_{$`}=$' for split$",pop@p: for each (for) assignment (split$") in the last machine description line (@p), locate equal sign (/=/) then assign value $' to hask %_ key $`
$o='\w+': initial state would be first one to match Perl regex "word characters"
until/"/: loop until we reach a termination state:

map{($r,$o,$,,$b)=$'=~/".*?"|\S+/g if/^$o :/}@p: loop on machine description @p: when we're on the line matching current state (if/^$o :/), tokenize (/".*?"|\S+/g) the rest of the line $' to variables ($r,$o,$,,$b).  Trick: the same variable $o if used initially for label name and subsequently for operator.  As soon as the label matches, the operator overrides it, and as a label can't (reasonably) be named + or -, it never matches again.
$_=$o=($_{$r}+=','cmp$o)<0?do{$_{$r}=0;$b}:$,:- adjust target register $_{$r} up or down (ASCII magic: ','cmp'+' is 1 whereas ','cmp'-' is -1);- if the result is negative (<0?, can only happens for -)- then stay at 0 ($_{$r}=0) and return second label $b;- else return first (possibly sole) label $,
BTW, it's $, instead of $a so it can be glued to next token until with no whitespace in between.

say for eval,%_: dump report (eval) and contents of registers in %_


Interpret loose ranges Interpret loose ranges
ListSharp is an interpreted programming language that has many features, one of those features is a 1 index based range creator that works like this:
You define a range as (INT) TO (INT) or just (INT) where both or the single int can go from min to max int32 value
Then you can use those ranges to extract elements of an array without fearing to overstep it's boundaries

therefore:
1 TO 5 generates: {1,2,3,4,5}
3 generates: {3}
Ranges can be added up using the AND operator
1 TO 5 AND 3 TO 6 generates: {1,2,3,4,5,3,4,5,6}
remember this works with negative numbers as well
3 TO -3 generates: {3,2,1,0,-1,-2,-3}

The challenge is the following:
Input
A character array and the previously defined range clause as a string
Output
The elements at the 1 index based locations of the range (non existing/negative indexes translate to an empty character)

How to win
As a code-golf challenge you are supposed to create the program with the shortest byte count to win

It has been pointed out empty characters do not exist, therefore you should be ignoring them (I only showed them here to make it easier to understand yet it confused people)
Test cases:
input array is:
{'H','e','l','l','o',' ','W','o','r','l','d'}

range clause:
"1 TO 3" => "Hel"
"5" => "o"
"-10 TO 10" => "Hello Worl"
"0 AND 2 AND 4" => "el"
"8 TO 3" => "oW oll"
"-300 AND 300" => ""
"1 TO 3 AND 3 TO 1" => "HelleH"
"-20 TO 0 AND 1 AND 4" => "Hl"

Python 2 - 239 211 210 bytes

Thanks to @mbomb007 and @Cyoce for further golfing this solution!

def r(s):
 t=[]
 for x in s.split("AND"):
  if"T"in x:a=map(int,x.split("TO"));b=2*(a[0]<a[1])-1;t+=range(a[0],a[1]+b,b)
  else:t+=int(x),
 return t
lambda p,v:[(['']+p+['']*max(map(abs,r(v))))[x]for x in r(v)]

Straight-forward approach. Tried generators and a recursive version, but they couldn't beat the simple for each loop. I'm a golfing noob, so this can most likely be improved quite a bit. Also, the major flaw of this snippet is that the range as a list object is computed again each time an element is retrieved from the character array (see last line, list comprehension). This means r(s) is executed len(r(s)) + 1 times.

Ungolfed code:

def find_range(string):
    result = []

    # Split at each AND and look at each element separately
    for element in string.split("AND"):
        # Element is just a number, so add that number to the result list
        if "TO" not in string:
            result += [int(string)]

        # Generate a list with all the values in between the boundaries
        # (and the boundaries themselves, of course) and append it to the result list
        else:
            boundaries = map(int, string.split("TO"))
            ascending = boundaries[0] < boundaries[1]

            # range(start, stop, step) returns [start, ..., stop - 1], so extend the stop value accordingly
            # range(8, 3, 1) returns just [], so choose respective step (negative for a descending sequence)
            result += range(boundaries[0], boundaries[1] + (1 if ascending else -1), 1 if ascending else -1)

# Make the char array 1-indexed by appending an empty char in 0th position
# Add enough empty chars at the end so too large and negative values won't wrap around
interpret = lambda chars, range_expr: [(['']+chars+['']*max(map(abs, find_range(range_expr))))[x] for x in find_range(range_expr)]

Test cases:

c = list("Hello World")
print interpret(c, "1 TO 3")
print interpret(c, "5")
print interpret(c, "-10 TO 10")
print interpret(c, "0 AND 2 AND 4")
print interpret(c, "8 TO 3")
print interpret(c, "-300 AND 300")

Output:

['H', 'e', 'l']
['o']
['', '', '', '', '', '', '', '', '', '', '', 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l']
['', 'e', 'l']
['o', 'W', ' ', 'o', 'l', 'l']
['', '']


Create a Simon Clone! Scenario: while programming you have a sudden nostalgic urge for the '80s and cheesy games.

Requirements: Make a GUI program (text probably won't work) for Simon, the game. Input can be clicking, or pressing a key. You should divide the screen into 4 regions: yellow, blue, red, green. When the game starts, a random color lights up and you activate it. Then, two lights come on, one after the other, and you need to activate those in order, etc. The game ends when you press the wrong color.

Bonuses:

-100 if you include sound (a different note played when pressing each region and when the game shows you the colors)

-25 if you include a score counter.

Scratch, 1604 – 125 = 1479

I'm here for the fun, not the golf.

Edit: updated scoring method based on community consensus.

Main program:

Individual sprites:

This is the sprite with number 0. The other sprites have the same script, except the number.

Play with it online.

Code used for byte counting: (Using snippet to hide code)

when green flag clicked
set [s v] to [0]
delete (all v) of [a v]
forever
  set [x v] to (pick random (0) to (3))
  add (x) to [a v]
  set [i v] to [1]
  repeat (length of [a v] :: list)
    broadcast (item (i) of [a v] :: list)
    wait (0.3) secs
    change [i v] by (1)
  end
  set [i v] to [1]
  wait until <(x) = [4]>
end

when I receive [0 v]
play sound [0 v]
next costume
wait (0.3) secs
next costume

when this sprite clicked
broadcast [0 v]
wait (0.3) secs
if <[0] = (item (i) of [a v] :: list)> then
  change [i v] by (1)
else
  stop [all v]
end
if <(i) > (length of [a v] :: list)> then
  set [x v] to [4]
  change [s v] by (1)
end

when this sprite clicked
broadcast [3 v]
wait (0.3) secs
if <[3] = (item (i) of [a v] :: list)> then
  change [i v] by (1)
else
  stop [all v]
end
if <(i) > (length of [a v] :: list)> then
  set [x v] to [4]
  change [s v] by (1)
end

when I receive [3 v]
play sound [3 v]
next costume
wait (0.3) secs
next costume

when I receive [1 v]
play sound [1 v]
next costume
wait (0.3) secs
next costume

when this sprite clicked
broadcast [1 v]
wait (0.3) secs
if <[1] = (item (i) of [a v] :: list)> then
  change [i v] by (1)
else
  stop [all v]
end
if <(i) > (length of [a v] :: list)> then
  set [x v] to [4]
  change [s v] by (1)
end

when this sprite clicked
broadcast [2 v]
wait (0.3) secs
if <[2] = (item (i) of [a v] :: list)> then
  change [i v] by (1)
else
  stop [all v]
end
if <(i) > (length of [a v] :: list)> then
  set [x v] to [4]
  change [s v] by (1)
end

when I receive [2 v]
play sound [2 v]
next costume
wait (0.3) secs
next costume

Note: Code automatically generated using scratchblocks generator, modified as somehow the generator doesn't correctly handle decimal numbers (treating 0.3 as 0).

Screenshot:

Note: Please do not press two buttons within 0.3 seconds.


Check B-powersmoothness from Wikipedia, a number is called B-powersmooth if all prime powers \$p^v\$ that divide the number satisfy \$p^v \leq B\$. B-powersmoothness is important, for example, for Pollard's p-1 factorization algorithm.
Task
your task is to get two numbers, \$n\$ and \$B\$, and output if \$n\$ is \$B\$-powersmooth.
Rules

You may take the input in any reasonable format
Since this is code-golf, the shortest code wins.
You can output a truthy/false value, or any two different values for true/false.
You can assume \$ 1 < B, n \$.

Test cases
n, b -> answer
3, 2 -> 0
10, 7 -> 1
123, 40 -> 0
123, 41 -> 1
64, 2 -> 0
64, 32 -> 0
64, 65 -> 1
720, 5 -> 0
720, 15 -> 0
720, 16 -> 1
20, 5 -> 1

J, 14 13 bytes
<[:>./2^/@p:]

Try it online!
-1 byte thanks to @Jonah
A dyadic function. The right argument is \$n\$, the left argument is \$B\$. Returns 0 if \$n\$ is \$B\$-powersmooth, 1 otherwise.
How it works
<[:>./2^/@p:]  NB. left arg = B, right arg = n
      2   p:]  NB. Prime factorization of n,
               NB. given as a 2-row matrix of [primes, exponents]
       ^/@     NB. Evaluate all pi^ei for each prime factor
 [:>./         NB. Maximum of all prime powers found above
<              NB. 1 if the above is greater than B, 0 otherwise


Find the closest three-digit hex colour In CSS, colours can be specified by a "hex triplet" - a three byte (six digit) hexadecimal number where each byte represents the red, green, or blue components of the colour. For instance, #FF0000 is completely red, and is equivalent to rgb(255, 0, 0).

Colours can also be represented by the shorthand notation which uses three hexadecimal digits. The shorthand expands to the six digit form by duplicating each digit. For instance, #ABC becomes #AABBCC.

Since there are fewer digits in the hex shorthand, fewer colours can be represented.

The challenge

Write a program or function that takes a six digit hexadecimal colour code and outputs the closest three-digit colour code.

Here's an example:

  Input hex code: #28a086
  Red component

  0x28 = 40 (decimal)
  0x22 = 34
  0x33 = 51
  0x22 is closer, so the first digit of the shortened colour code is 2

  Green component

  0xa0 = 160
  0x99 = 153
  0xaa = 170
  0x99 is closer, so the second digit is 9

  Blue component

  0x86 = 134
  0x77 = 119
  0x88 = 136
  0x88 is closer, so the third digit is 8

  The shortened colour code is #298 (which expands to #229988)

Your program or function must accept as input a six digit hexadecimal colour code prepended with # and output a three digit colour code prepended with #.

Examples

#FF0000 → #F00
#00FF00 → #0F0
#D913C4 → #D1C
#C0DD39 → #BD3
#28A086 → #298
#C0CF6F → #BC7

Scoring

This is a code-golf challenge, so shortest answer in your language wins! Standard rules apply.


Your Oscilloscope has ExPloDEd ! Make a sine wave [ CODE GOLF]

BAM! - Fire and Smoke
Your Oscilloscope has exploded from one too many waves.

Re-create these waves assuming the following:

All waves are Sine Waves

An amplitude of 1 spans 3 lines (Therefore and amplitude of 2 would span 5 lines) [Vertically]

We want to see 100 characters worth of sine (Can be any char) [Horizontally]

12 characters per Period is a frequency of 1Hz

[Amplitude of 1 and Frequency of 1Hz with a Span of 45 Characters]
>SinASCII('a1','f1')

   ...         ...         ...             >
...   ...   ...   ...   ...   ...   ...    >[cont. for 100 char]
         ...         ...         ...       >

Inputs
Inputs can be in any format but must be explicitly stated if different from standard (below) and must contain:

Amplitude
Frequency

Test inputs:  [('a2', 'f0.5'), ('a4', 'f1'), ('a6', 'f2'), ('a1','f0.25')]

This is a CODE GOLF Challenge
Some Clarification
Because sine is a continuous function, the values must be discretized:
For the case of amplitude of 1 and frequency of 1Hz the "Crest" of the sine wave must be on line 1 and the "Trough" of the sine wave must be on line 3.
To achieve the intermediate points, the wave points are set corresponding to ranges associated to the sections of the wave and these ranges will be relative to the amplitude.
Wikipedia - Crest and Trough

Python 3, 128 \$\cdots\$ 107 103 bytes

Added a byte to fix and error kindly pointed out by blueteeth.
Saved 23 27 bytes thanks to Jonathan Allan!!!
Added a byte to fix a fudge kindly pointed out by Jonathan Allan.

lambda a,f:[[' .'[~j<=a*sin(f*i*pi/6)+.5<-j]for i in range(100)]for j in range(~a,a)]
from math import*

Try it online!

Inputs an integral amplitude and a float for frequency.
Uses a period of 12 characters for 1Hz.
Returns a list of lists of characters.


Square-Random-Symmetrical Challenge

Write a program or a function that returns or prints a square-random-symmetrical matrix.

Input

N: The size of the matrix i.e 6 x 6

Output

The matrix. You can either print it, return it as string (with the newlines) or as a list/array of lists/arrays.

Rules

You need to use at least N different characters, where N is the size of the square matrix (input). Since we 're using only letter [a, z][A, Z] and digits [0, 9] (and only 1 digit at the time) you can assume that N < 27 and N > 2, that is because at N <= 2 you can't have both letters and digits. Last but not least, every letter/digit must have non-zero probability of occurring (uniform distribution is not a necessity). However, the result must have at least N different letter/digits.
The matrix has to be both horizontally and vertically symmetrical.
Exactly 2 rows and 2 columns must contain strictly one single-digit number (it's position should be random as well). The rest of rows/cols will contain only letters. Consider letters as [a, z] and [A, Z] and of course single-digit numbers as [0, 9].
Just to be easier, you can assume that the case of the letters doesn't matter, as long as the cases are symmetrical which means: a=A, b=B, etc.
Every possible output must have a non-zero probability of occurring. The random distribution doesn't need to be uniform.

Example

Input: 8

Output:

c r p s s p r c
r k o z z o k r
u t 2 a a 2 t u
y n q z z q n y
y n q z z q n y
u t 2 a a 2 t u
r k o z z o k r
c r p s s p r c

R, 124 118 bytes

function(n,i=(n+1)/2,j=n%/%2,m="[<-"(matrix(-letters,i,i),j-1,j-1,0:9-1))cbind(y<-rbind(m,m[j:1,]),y[,j:1])
`-`=sample

Try it online!

In R, things that look like operators are just functions that get special treatment from the parser.

If you redefine an operator (like -) to be some other function, it keeps the special treatment from the parser. Since - is both prefix and infix, and I need to call the sample function with both one and two arguments, I can use

`-`=sample

to get what I want.

So the code -letters is translated to sample(letters), which randomly shuffles the letters built-in. But j-1 is translated to sample(j,1), which randomly samples 1 item from the vector 1:j.

(This behaviour of the sample function depending on the number of parameters and what the first parameter is, is a huge pain in the butt in production code, so I'm happy to find a great use of its perverse nature here!)

Otherwise the code just makes the top left quadrant of the required result, replaces a random element (the j-1,j-1 bit) with a random digit (the 0:9-1 bit), and folds it out for the required symmetry. The i and the j are needed to deal with the even and odd cases.


Error 404: Character Not Found Scenario

One of your friends is struggling on a homework assignment. He needs a simple program which prints the first 404 natural numbers:

1 2 3 4 5 6 7 8 9 10 11 ... 401 402 403 404

Your challenge is simple: write this program for him.

However, your connection is terrible, so 1 random character is lost every time you send the program. To prevent this from breaking your program, you must make it so that removing any single character will have no effect: the program works, regardless. (The original program must also work.)

Because the connection is too poor to send large files, your code must be as short as possible.

TL:DR - make a radiation hardened program to output the numbers 1 to 404

Rules/Details

The output may be a list of integers in any reasonable format (separated by spaces, newlines, commas, etc). However, your output must be consistent and not change when the program is modified.
Command line flags that contain logic, execute actual code, generate the number list, and so on, are banned.
This is code-golf, so the shortest submission (in bytes) wins!

JavaScript, 228 bytes

etInterval=stInterval=seInterval=setnterval=setIterval=setInerval=setIntrval=setInteval=setInteral=setIntervl=setInterva=top=>4

setInterval
`405>(i=this.i?i:1)?alert(i++):0`///`
setInterval
`405>(i=this.i?i:1)?alert(i++):0`///`

Explanation

Evaluating code in a setInterval allows the program to continue even if there is an error. We make sure that the code passed will error out if any single character is removed. Template string syntax can be abused to call setInterval with a constant string without parentheses. Luckily, even if the template string is on the next line it still parses as a function call with such syntax.

The first issue we run into is that setInterval is a function, and thus if a character is removed and the program tries to call setInteval instead, it errors out. Of course, since there are two indentical invocations of the setInterval, we don't have to worry about it actually functioning correctly as long as we avoid the error. So, the first line defines every possible "misspelling" of setTimeout to a valid function.

The first line works by assigning all of these "misspellings" to the function top=>4. Note the ES6 syntax, this simply takes a paramater named "top" and returns 4. Why "top"? Well, the first line must never throw an error even if a character is removed. If an = is removed to make top>4, this boolean expression will be valid since top is predefined in browsers, simply yielding false. If the 4 is removed, the function body simply becomes the first setInterval segment, and the second runs unharmed.

Now, all that is left to worry about is if a ` is removed.

If removed from the beginning, setInterval simply does nothing, evaluating to itself as its own expression. Then, the rest of the second line simply runs a single iteration of the loop, letting the other setInterval fragment finish the job. If removed from the end, the remaining backtick is picked up from the end of the comment.

The newlines are placed so that removal one will not affect program behavior, but they prevent errors in the case of some character removals such as the leading backtick.


How predictable is popular music? The McGill Billboard Project annotates various audio features of songs from a random sample of the Billboard charts. I scraped this data to produce the following file of chord progressions:

chords.txt

Write the shortest code that outputs the above file (or its contents).

Edit: Here's a quick description of the notation to get you started:

N denotes no chord.
A:min denotes the A minor triad chord.
C#:sus4(b7,9) and other spicy chords are completely described here.


Antisymmetry of a Matrix A matrix is antisymmetric, or skew-symmetric, if its transpose equals its negative.
The transpose of a matrix can be obtained by reflecting its elements across the main diagonal. Examples of transpositions can be seen here:
\$\begin{pmatrix}11&12&13\\21&22&23\end{pmatrix}\rightarrow\begin{pmatrix}11&21\\12&22\\13&23\end{pmatrix}\$
\$\begin{pmatrix}11&12&13\\21&22&23\\31&32&33\end{pmatrix}\rightarrow\begin{pmatrix}11&21&31\\12&22&32\\13&23&33\end{pmatrix}\$
This matrix is antisymmetric because it equals its transpose when multiplied by -1:
\$\begin{pmatrix}0&2&-1\\-2&0&0\\1&0&0\end{pmatrix}\$
All antisymmetric matrices exhibit certain characteristics:

Antisymmetry can only be found on square matrices, because otherwise the matrix and its transpose would be of different dimensions.

Elements which lie on the main diagonal must equal zero because they do not move and consequently must be their own negatives, and zero is the only number which satisfies \$x=-x\$.

The sum of two antisymmetric matrices is also antisymmetric.

The Challenge
Given a square, non-empty matrix which contains only integers, check whether it is antisymmetric or not.
Rules

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

Input and output can assume whatever forms are most convenient as long as they are self-consistent (including output which is not truthy or falsy, or is truthy for non-antisymmetry and falsy for antisymmetry, etc).

Assume only valid input will be given.

Test Cases
In:
1 1 1
1 1 1
1 1 1

Out: False

In:
 0 0 1
 0 0 0
-1 0 0

Out: True

In:
0 -2
2  0

Out: True

APL (Dyalog Unicode), 3 bytes

-≡⍉

Try it online!
This is exactly an APLcart entry on "antisymmetric". Basically it checks if the input's negative - matches ≡ the input's transpose ⍉.


Algorithm - Costliest Possible Route in Grid Puzzle Objective

Find the most expensive path from the top-left of a square grid to the bottom-right such that its total cost is below a given threshold.

Scenario

You are given a square NxN grid.
You are given a maximum cost.
Every cell in the grid has a cost. The top-left cell has cost 0.
The cost of a path is the sum of the costs of the cells in the path. Its "cost surplus" is the result of subtracting its cost from the maximum cost.
Movement is always either right one cell or down one cell.
The starting point is the top-left cell of the grid and the goal is the bottom-right cell.
You must output the smallest cost surplus of any path with a non-negative cost surplus, or -1 if there is no such path (The maximum cost is not enough).

Input restrictions

N will be between 1 and 20 inclusive.
The maximum cost will be between 1 and 200 inclusive.
The cost of each cell will be between 0 and 10 inclusive.

Examples

Maximum cost: 9
Grid:

0 1 5
2 3 2
2 3 2

Expected output: 0
Explanation: there is a path 0 2 2 3 2 with cost 9 and cost surplus 0.
Maximum cost: 15
Grid:

0 1 5
2 3 2
2 3 2

Expected output: 5
Explanation: the most expensive path is 0 1 5 2 2 with cost 10 and cost surplus 5.
Maximum cost: 6
Grid:

0 1 5
2 3 2
2 3 2

Expected output: -1
Explanation: the least expensive path is 0 1 3 2 2 with cost 8, which is greater than 6.

CJam, 72 71 bytes
q~:Q,mqi:L(2*0aa\{{_[~__)L%1L?+]\[~__L/)L=1L?+]}%}*{Qf=:+}%f-{W>},$W+0=

This is really long and I think a different approach to the question is the only way to get it shorter.
Try it online here
Input is in the following format : <Steps> [<Flat Grid>] . For ex:
9 [0 1 5 2 3 2 2 3 2]

And output is the cost remaining, so 1 in above example.
*Note that [0 1 5 2 3 2 2 3 2] is just a flat representation of the grid
0 1 5
2 3 2
2 3 2

How it works (slightly outdated):
q~                                     "Read the input and evaluate it";
  :Q                                   "Store the array in Q";
    ,mqi:L                             "Do floor of square root of its length";
          LL+((                        "Double length and decrease 2 from the double";
               0aa                     "Put [[0]] on stack. This is the starting index"
                                       "for any path in the grid";
                  \{ ... }*            "Swap to but L + L - 1 on top and run the code"
                                       "block that many times";
 {{_[~__)L%1L?+]\[~__L/)L=1L?+]}%}*    "This block calculates indexes of all possible";
                                       "paths from top left to bottom right of the grid";
 {                            }%       "Map each array based on this code block";
  _[~                                  "Copy the array and start a new array with the"
                                       "contents of the copied one";
     __                                "Make two copies of the last element of the array";
       )L%                             "Increment the element and calculate module L";
          1L?                          "Choose L if module is 0, 1 otherwise";
             +]                        "Add it to the copy of last array element. With"
                                       "this, we have created one of the two possible"
                                       "next step, that is going right. Except if we are"
                                       "on the last column, then go down";
               \[~                     "Swap and start a new array with contents of"
                                       "the original array";
                  __                   "Make two copies of the last element";
                    L/)                "Divide the 2nd copy by L and add 1 to the result";
                       L=1L?           "If index belongs to last row, choose 1, else L";
                            +]         "Add to the first copy of last element and close"
                                       "the array. Now we have the second possible next"
                                       "step, i.e. going down. But if we are on last row"
                                       "then go right";
{Qf=:+}%                               "Map this block on the array containing all"
                                       "possible path indexes";
 Qf=                                   "Get the corresponding cell amount array";
    :+                                 "Sum the array elements to get total path cost";
        {1$)<},                        "Filter out paths which are not possible. i.e."
                                       "paths having total cost more than first input";
               $W=                     "Sort and get the last (highest) path cost";
                  -                    "decrement from input to get remaining steps";


Alternating Sign Sequence Introduction

The sign of a number is either a +, or a - for every non-zero integer. Zero itself is signless (+0 is the same as -0). In the following sequence, we are going to alternate between the positive sign, the zero and the negative sign. The sequence starts with 1, so we write 1 with a positive sign, with zero (this one is weird, but we just multiply the number by 0) and the negative sign:

1, 0, -1

The next number is 2, and we do the same thing again:

2, 0, -2

The sequence eventually is:

1, 0, -1, 2, 0, -2, 3, 0, -3, 4, 0, -4, 5, 0, -5, 6, 0, -6, 7, 0, -7, ...

Or a more readable form:

a(0) = 1
a(1) = 0
a(2) = -1
a(3) = 2
a(4) = 0
a(5) = -2
a(6) = 3
a(7) = 0
a(8) = -3
a(9) = 4
...

The Task

Given a non-negative integer n, output the nth term of the above sequence. You can choose if you use the zero-indexed or one-indexed version.

Test cases:

Zero-indexed:

a(0) = 1
a(11) = -4
a(76) = 0
a(134) = -45
a(296) = -99

Or if you prefer one-indexed:

a(1) = 1
a(12) = -4
a(77) = 0
a(135) = -45
a(297) = -99

This is code-golf, so the submission with the smallest number of bytes wins!

JavaScript ES6, 18 bytes

n=>-~(n/3)*(1-n%3)

Turned out very similar to @LeakyNun's answer but I didn't see his until after I posted mine.

Explanation and Ungolfed

-~ is shorthand for Math.ceil, or rounding up:

n =>               // input in var `n`
    Math.ceil(n/3) // Get every 3rd number 1,1,1,2,2,2, etc.
    *
    (1-n%3)        // 1, 0, -1, 1, 0, -1, ...

function f(n){n=i.value;o.value=-~(n/3)*(1-n%3);}
Input: <input id=i oninput="f()"/>

Output: <input id=o readable/>


Magic Square Challenge For the purpose of this question, a magic square is an n×n square of (not necessarily distinct) positive integers, where all rows, columns, and main diagonals add to a "magic constant" m.

Your Task

Create a function or full program that, given the magic number m and a list representing a square with at most one wrong number in each row and column, will output a list with the entries rearranged to represent a correct square. Your program will be expected to handle any solvable square of any size. Your program should take less than twenty minutes for n=7 or smaller. Assume that all input is solvable.

Example Input (list, m)

[16, 16, 11, 9, 14, 17, 9, 29, 13, 1, 15, 5, 6, 16, 15, 7, 3, 17, 11, 12, 14, 17, 3, 8, 6], 58

which represents this square1:

  16 16 11 09 14
   17 09 29 13 01
   15 05 06 16 15
   07 03 17 11 12
   14 17 03 08 06

A compliant solution has to solve the following 7x7 square within the time limit.

[31, 19, 10, 13, 14, 32, 15, 6, 21, 17, 22, 30, 17, 7, 17, 30, 17, 24, 17, 11, 8, 7, 22, 33, 13, 15, 17, 11, 14, 16, 21, 22, 13, 11, 29, 16, 13, 3, 19, 12, 12, 43, 27, 13, 19, 13, 20, 18, 11], 123

Example Output

For the first test case, this is the only correct solution.

[16, 16, 3, 9, 14, 6, 9, 29, 13, 1, 15, 5, 6, 17, 15, 7, 11, 17, 11, 12, 14, 17, 3, 8, 16]

For a bonus of -10, format your output into a square and pad single digits with zeroes as below.2

  16 16 03 09 14
   06 09 29 13 01
   15 05 06 17 15
   07 11 17 11 12
   14 17 03 08 16

1 Bolded numbers are in incorrect cells.
2 Bolded numbers have switched cells.

CJam, 73 70 bytes

q~:Q,mQ:Le!{QL/.{1$W$W*t_:+W*t}:Te_$Q$=Tz{W%_L,.=a\}2*++::+)-!*}=&T"%02d "ffe%N*

The above code is 80 bytes long and qualifies for the bonus.

Time complexity is O(n!) for n×n squares. For 9×9, this translates to 7 seconds on my machine.

Try it online: permalink for Chrome | permalink for Firefox


Sequences of distinct positive integers The goal of this challenge is to take a positive integer n and output (in lexicographic order) all sequences \$S = [a_1, a_2, ..., a_t]\$ of distinct positive integers such that \$\max(S) = n\$.
For example, for an input n = 3 your program should output the following eleven sequences in the following order:
[
  [1, 2, 3],
  [1, 3],
  [1, 3, 2],
  [2, 1, 3],
  [2, 3],
  [2, 3, 1],
  [3],
  [3, 1],
  [3, 1, 2],
  [3, 2],
  [3, 2, 1],
]

(In general, for an input n, your program should output \$A001339(n-1)\$ sequences.)

This is a code-golf challenge, so the shortest code wins.

Python 2, 78 bytes

f=lambda n,l=[]:sum([f(n,l+[i+1])for i in range(n)if~-(i+1in l)],[l]*(n in l))

Try it online!
Python 3 lets us save some bytes with set unpacking.
Python 3, 74 bytes

f=lambda n,l=[]:sum([f(n,l+[i])for i in{*range(1,n+1)}-{*l}],[l]*(n in l))

Try it online!


Give a multiple choice test I present to you a test! Your test is to test. The test is to test the testee with tests a tester gives you, in the shortest amount of code. Specifically, you will give a multiple choice test that you have recieved as input.

In this challenge, you must take an input like this:

1. Our site is called Programming Puzzles & Code ________.
A: Debugging
*B: Golf
C: Hockey
D: Programming
2. What is the *most* popular tag on our site?
A: [debug]
B: [program]
*C: [code-golf]
D: [number]
E: [c++]
3. We are part of the ________ Exchange network.
*A: Stack
B: Code
C: Programmer
D: Hockey
4. Is this the first question?
A: Yes
*B: No
5. Is this the last question?
*A: Yes
B: No

And here is an example of the test being taken:

1. Our site is called Programming Puzzles & Code ________.
A: Debugging
B: Golf
C: Hockey
D: Programming
answer: B
correct!

2. What is the *most* popular tag on our site?
A: [debug]
B: [program]
C: [code-golf]
D: [number]
E: [c++]
answer: C
correct!

3. We are part of the ________ Exchange network.
A: Stack
B: Code
C: Programmer
D: Hockey
answer: B
incorrect! the answer was A

4. Is this the first question?
A: Yes
B: No
answer: B
correct!

5. Is this the last question?
A: Yes
B: No
answer: B
incorrect! the answer was A

overview:
3 correct, 2 incorrect (60%)

3. We are part of the ________ Exchange network.
you chose B: Code
the answer was A: Stack

5. Is this the last question?
you chose B: No
the answer was A: Yes

Formal specification:

Input

If a line begins with a number followed by a dot and a space, it is a question with that number. Numbers will always start from 1 and go up 1 each question.
If a line begins with an optional asterisk, a letter, a colon, and then a space, it is an answer. Answers will also always be sequential. There will be only one correct answer per question.
A line will not begin in any other way than the previously mentioned ways.
Input may be accepted in any way (reading from a file, stdin, etc.) but must not be hardcoded into your program.

Output (test-taking phase)

First, print out each question sequentially. Print the question and its answers as recieved in input, but do not print the asterisk indicating correct answers.
Then, print a newline and "answer: ". Wait for user input. User input will always correspond to an answer.
If the correct answer (the one with an asterisk) is the same as the one the user input, output "correct!". Otherwise, output "incorrect! the answer was " + correct_letter.
Separate each question with a blank line, then repeat the previous output steps until there are no more questions.

Output (overview phase)

Print "overview: " and then a newline.
Print "{number of correct answers} correct, {incorrect answers} incorrect ({percent correct, rounded to the nearest whole number}%)" (of course substituting the phrases in curly braces with their respective values). Then print a blank line for spacing.
Now, for each question that was wrong, print the question (not its answers), then on a new line "you chose " + answer_you_chose, and on another line "the answer was " + correct_answer. Separate each wrong answer's overview with a blank line.

In order to reduce cheating by interpreting things literally, when given the same output here, and the same input in the test-taking phase, your program must output exactly the same thing as the sample output.

This is code-golf; shortest code wins! (And gets an A+ (green checkmark)!)

Mathematica 144
This may be an invalid attempt. I separated the question from each answer in the input. I also indicated the correct answer by a letter in a separate field, rather than an asterisk before the alternative.
Anyway...
The Data
questions={{{"\n1. Our site is called Programming Puzzles & Code ________.\n","A: Bugging\n","B: Golf\n","C: Hockey\n","D: Programming\n"},"B"},{{"\n2. What is the most popular tag on our site? \n","A: [debug]\n","B: [program]\n","C: [code golf]\n","D: [number]\n"},"C"},{{"\n3. We are part of the _______ Exchange network. \n","A: Stack\n","B: Code\n","C: Programmer\n","D: Hockey\n"},"A"},{{"\n4. Is this the first question? \n","A: Yes\n","B: No\n"},"B"},{{"\n5. Is this the last question? \n","A: Yes\n","B: No\n"},"A"}};

Code
An answer to each question is entered through a dialog box.
Questions, answers, and feedback are printed.
f@x_:=
Print[If[((r=ChoiceDialog[Print[""<>#,"\nanswer: "];""<>#,StringTake[Rest@#,1]])==#2),
r<>"\ncorrect!", r<>"\nincorrect, the answer is "<>#2]&@@x]

Test
f /@ questions


Generating Minesweeper grids Minesweeper is a logic game found on most OS's. The goal of the game is to determine where the mines are on a grid, given numbers indicating the number of mines around that spot.

Given a grid size, and a set of mines, generate the Minesweeper grid for that set of mines.

Input: Two integers indicating the grid size, and an undefined number of integers indicating the mine positions. Positions will be given as (column position, row position), and the indexes will start at row 1.

Output: The Minesweeper grid. If there are no mines around a block, print an x. For each new row, print a newline. Please output all mines as an asterisk *. Do not leave any whitespace between the values in the row when printing.

Test Cases:

Input "5 5 1 3 3 5 2 4":

xxxxx
11xxx
*21xx
2*21x
12*1x

Input "3 4 3 1 1 4 2 3 3 2":

x2*
13*
2*2
*21

Shortest code wins.


Name of Frankenstein's Monster Introduction:
Since it's almost Halloween, I was just thinking of some random Halloween-themed challenges. Eventually I was reading through Frankenstein's wikipedia page, and came across the following text:

The creature
Part of Frankenstein's rejection of his creation is the fact that he does not give it a name, which causes a lack of identity. Instead it is referred to by words such as "wretch", "monster", "creature", "demon", "devil", "fiend", and "it". When Frankenstein converses with the creature in Chapter 10, he addresses it as "vile insect", "abhorred monster", "fiend", "wretched devil", and "abhorred devil".

source
Challenge:
Given two integers (year and chapter), output a string based on the following rules:

If the year is less than 1818: output an empty string †
If the year is exactly 1818 and the chapter is below 10: output a random string from the list ["wretch", "monster", "creature", "demon", "devil", "fiend", "it"]
If the year is exactly 1818 and the chapter is 10 or higher: output a random string from the list ["vile insect", "abhorred monster", "fiend", "wretched devil", "abhorred devil"]
Is the year above 1818 (and thus the book was published), return "Frankenstein's Monster".

Challenge rules:

You can choose whether to output in lowercase, uppercase, or a combination.
The year will always be in the range 1500-2017
The chapter will always be in the range 1-24 (if I googled correctly, the book has 24 chapters)
† Instead of outputting an empty string for option 1, you are also allowed to output null, undefined, false, 0, or any other value of your choice not part of the other three options (please specify what you've used in your answer).
The output may not contain any leading or trailing spaces/tabs, nor any leading new-lines. It may contain one optional trailing new-line.

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, full programs. Your call.
Default Loopholes are forbidden (especially 'Fake random numbers').
If possible, please add a link with a test for your code.
Also, please add an explanation if necessary.

Test cases:
year,chapter possible outputs:

1700,1       ""; null; undefined; false; 0; etc.
1700,12      ""; null; undefined; false; 0; etc.
1817,10      ""; null; undefined; false; 0; etc.
1818,1       "wretch"; "monster"; "creature"; "demon"; "devil"; "fiend"; "it"
1818,9       "wretch"; "monster"; "creature"; "demon"; "devil"; "fiend"; "it"
1818,10      "vile insect"; "abhorred monster"; "fiend"; "wretched devil"; "abhorred devil"
1818,11      "vile insect"; "abhorred monster"; "fiend"; "wretched devil"; "abhorred devil"
1818,18      "vile insect"; "abhorred monster"; "fiend"; "wretched devil"; "abhorred devil"
1819,1       "Frankenstein's Monster"; "frankenstein's monster"; "FRANKENSTEIN'S MONSTER"
1819,18      "Frankenstein's Monster"; "frankenstein's monster"; "FRANKENSTEIN'S MONSTER"
2017,24      "Frankenstein's Monster"; "frankenstein's monster"; "FRANKENSTEIN'S MONSTER"

Python 2, 227 220 214 bytes

lambda y,c:[[choice([["wretch",m,"creature","demon",d,F,"it"],["vile insect",a+m,F,"wretched "+d,a+d]][c>9]),"Frankenstein's "+m][y>1818],0][y<1818]
from random import*
m,d,F,a='monster','devil','fiend',"abhorred "

Try it online!


Tips for golfing in APL I started one code golf challenge recently and it seems like the winner is GolfScript (surprise, surprise!). What's interesting is that there was another very strong competitor that had all chances to win over GolfScript. Its name is APL. I see a lot of answers written in APL here. It seems like this language is fairly efficient for code golfing, so I decide to ask for any code golfing tips you know for APL programs. Feel free to post some code examples. It is usually very interesting to see language in action.

Edit: for people reading this who don't  know APL at all but want  to take it up, Mastering Dyalog APL is a very good resource.

Evaluation is strictly right-to-left. This includes setting variables, so take advantage of it.
2+a, 1+a←1  -> 3 4
a is set to 1, 1+a evaluates to 2, a,2 evaluates to 1 2 and 2+1 2 evaluates to 3 4.

Like C, ← can be combined with a function, i.e. a +← 3. Unlike C, this is generic: foo F← bar sets foo to F bar. Somewhat unintuitively, as an expression this returns bar, not F bar.
It works with anonymous functions too:
       a←0
       a+←3 ⋄ a
 3
       a+←3 ⋄ a
 6
       a { ⍵/'!' } ←4 ⋄ a
 !!!!

You can assign to an array: A[3]←8, like you'd expect. But you can also assign multiple items at the same time: A[3 5 6]←9 1 4, or even A[3 5 6]←9, setting them all to the same item. You can, of course, add a function to the ← here too. The  function will then be applied to each element separately, as if you did F¨.

⍨ is your friend, even if he doesn't look too happy about it.
1. If `F` is dyadic, dyadic `⍨` switches the arguments: `a F b` <-> `b F⍨ a`. This comes in handy when golfing because it can save you from using braces:

     (F G H x) K y      <->     y K⍨ F G H x

This does change the evaluation order, as the right hand is always evaluated before the left hand.

2. If `F` is dyadic, *monadic* `⍨` applies the same argument to both sides of the function:

           5⍴5
     5 5 5 5 5
           ⍴⍨5
     5 5 5 5 5

   The argument is only evaluated once. This particularly comes in handy with outer products, i.e. to compare each value in an array with the other values in the same array, you can use `∘.=⍨` instead of having to do `x∘.=x←(whatever)`.

3. If `F` is monadic, `⍨` does nothing, but it does separate the function from the argument. So it can still save you braces if the function is complex:

           {⍵+3}⍣5 6
           ∇{⍵+3}
          ∇ ⍣ 5 6
           ({⍵+3}⍣5)6
     21
           {⍵+3}⍣5⍨6
     21

Learn the idioms! Then golf the idioms. For example:
 ((((1↑⍴X),⍴Y)↑X)^.=Y)⌿X

can be mechanically transformed into:
 X⌿⍨Y^.=⍨X↑⍨(1↑⍴X),⍴Y

and then further into:
 X⌿⍨Y^.=⍨X↑⍨(⊃⍴X),⍴Y

⊃ (first) being equivalent to 1↑ (take one) in this case. And possibly:
 X⌿⍨Y^.=⍨X↑⍨(≢X),⍴Y

≢ (tally) being equivalent to ⊃⍴ (the first element of the shape) for all but scalars.


fit 22 (perhaps 23) of a specific 3d pentacube into a 5x5 cube Update: It seems that the original question at math.SE was solved, there should be no 23 pieces solution.
The original problem is stated here over at math.SE
The task is writing a program that fits 22 copies (or perhaps 23) of the following pentacube into a 5x5x5 cube (back and front view).

The pentacube must be placed within the grid (no 45° orientations and shifts of 0.5 etc.) of the big cube and can be rotated around any of the x,y,z axes in 90° steps.
Known up to now:
According to the math.SE question there is a solution for 22 pieces, but it is unknown whether there is a solution for 23 pieces. (24 again seems to be impossible).
Winning criteria
Rotatation and mirroring of one solution count all as the same solution. Finding all solutions means that the program must show that the solutions provided are really all possible solutions.
You will get (points will add up)

10 points for finding any 22 piece solution
20 points for finding two or more 22 piece solutions
50 points for finding all 22 piece solution
100 points for finding a 23 piece solution
200 points for finding two or more 23 piece solutions
500 points for finding all 23 piece solutions or showing that there is no 23 piece solution
1 point per vote

If two people have the same amount of points the one that postet first will win. Please explain your approach and show the solution/s (at least one if there is one.) Please also include your score (except votes) and the runtime in your answer. I discourage hardcoding answers. If you find solutions 'by hand' or if you find a mathematical proof you can also submit them, but please state this explicitly if you do so.
UPDATE: In the original post in math.SE now 64 solutions for 22 pieces have been found (non exhausive, and perhaps some of them are rotations/mirrorings of others). So I discourage just copying these solutions - but as long as you found them on your own this is ok!

Plane-based analysis, 30+ points

The basic idea is explained in the comment at the top of the class. This runs for about 8 minutes on my desktop and finds 90560 22-tile solutions, possibly including symmetrical ones; since a cube has only 48 isometries, that corresponds to at least 1887 distinct solutions. However, it doesn't guarantee that there are no more: only that if there are any more, they don't have two opposite exterior faces which contain 3 cubies each of 8.

Two sample solutions:

ddbee dubb. ruut. rlktt llkk.
adbbe aduee rrutt lrkjj lookj
aa.ff qa.f. .q.vv ioov. iiojj
ggchf qgcfh qqssv impnv mipnn
gcchh gcssh ...s. .m.pn mmppn

.ggff qqgf. .q.uu .llpu oolpp
bgddf bgvdf qqvu. ooiup ollip
bbdee rbdve rrvv. .mijj mmiij
hhcea rhcae .rstt kmsnt mknjj
hccaa hc.a. .sst. ks.nt kknn.

Checking for 23-tile solutions with the same principle is a matter of changing tilesInPlane2 to 7; it runs for about one minute and finds no solutions.

I suggest redirecting stdout to a file and watching the progress reports on stderr.

import java.util.*;

// Overall approach follows a strategy proposed by Ed Pegg.
// If we place one 8-tile board on plane 0 sticking into plane 1,
// and one 8-tile board on plane 4 sticking into plane 3,
// what can fit into plane 2 sticking into planes 1 and 3?
// Since an 8-tile plane occupies at least 16/25 of the adjacent plane, we're looking to fit 4/7 of the tiles from
// plane 2 into the gaps left by the tiles from plane 0, and then the remaining 3/7 into the gaps left
// by the tiles from plane 4.
public class CodeGolf36250 {
    // Bit mask: 25 bits indicating the "main" plane, 25 bits indicating the "adjacent" plane
    static final long mainPlane = (1L << 25) - 1;
    static final long adjPlane = ((1L << 25) - 1) << 25;

    static final int tilesInPlane2 = 6;
    static final int tilesInPlanes2_3 = (tilesInPlane2 + 1) / 2; // Half rounded up

    public static void main(String[] args) {
        Set<Long> primitives = new HashSet<Long>();
        for (int x = 0; x < 4; x++) {
            for (int y = 0; y < 4; y++) {
                int tl = x + y * 5;
                // We consider only positions where we put 3 cubies in the main plane and 2 in the adjacent plane.
                // Diagram format: main plane, adj plane
                // So we have
                //  c000 c100   c001 c101
                //  c010 c110   c011 c111
                long c000 = 1L << tl, c100 = c000 << 1, c010 = c000 << 5, c110 = c100 << 5;
                long c001 = c000 << 25, c101 = c100 << 25, c011 = c010 << 25, c111 = c110 << 25;
                // ##  .#  |  ##  #.  |  #.  #.  |  .#  .#
                // #.  #.  |  .#  .#  |  ##  .#  |  ##  #.
                primitives.add(c000 + c100 + c010 + c101 + c011);
                primitives.add(c000 + c100 + c110 + c001 + c111);
                primitives.add(c000 + c010 + c110 + c001 + c111);
                primitives.add(c100 + c010 + c110 + c101 + c011);
                // ##  .#  |  ##  ..  |  ##  #.  |  ##  ..
                // #.  .#  |  #.  ##  |  .#  #.  |  .#  ##
                primitives.add(c000 + c100 + c010 + c101 + c111);
                primitives.add(c000 + c100 + c010 + c011 + c111);
                primitives.add(c000 + c100 + c110 + c001 + c011);
                primitives.add(c000 + c100 + c110 + c011 + c111);
                // #.  .#  |  #.  ##  |  .#  #.  |  .#  ##
                // ##  .#  |  ##  ..  |  ##  #.  |  ##  ..
                primitives.add(c000 + c010 + c110 + c101 + c111);
                primitives.add(c000 + c010 + c110 + c001 + c101);
                primitives.add(c100 + c010 + c110 + c001 + c011);
                primitives.add(c100 + c010 + c110 + c001 + c101);
            }
        }

        // Building full sets of tiles in the two planes uses far too much memory in the intermediate numbers
        // (in particular, the 5-tile sets).
        // It's much more efficient to see what coverings of the main plane we get and then for the high-count
        // sets we care about, to expand them to the adjacent plane.
        List<Set<TileSet>> nTiles = new ArrayList<Set<TileSet>>();
        nTiles.add(new HashSet<TileSet>()); // 0 tiles
        nTiles.get(0).add(new TileSet());
        for (int n = 1; n < 9; n++) {
            Set<TileSet> next = new HashSet<TileSet>();
            for (TileSet board : nTiles.get(n - 1)) {
                for (long prim : primitives) {
                    if ((board.sum & prim) == 0) {
                        TileSet newBoard = new TileSet();
                        newBoard.addAll(board);
                        newBoard.add(prim & mainPlane);
                        next.add(newBoard);
                    }
                }
            }
            nTiles.add(next);
            System.err.println(n+" tiles: " + next.size());
        }

        // Needed for the expansion.
        Map<Long, Set<Long>> primsByMainPlane = new HashMap<Long, Set<Long>>();
        for (Long prim : primitives) {
            Set<Long> group = primsByMainPlane.get(prim & mainPlane);
            if (group == null) primsByMainPlane.put(prim & mainPlane, group = new HashSet<Long>());
            group.add(prim);
        }

        Map<Long, Set<TileSet>> boards8ByAdjGaps = new HashMap<Long, Set<TileSet>>();
        for (TileSet board8 : nTiles.get(8)) {
            for (TileSet expandedBoard8 : expand(board8, primsByMainPlane)) {
                long expansion = (~expandedBoard8.sum) & adjPlane;
                Set<TileSet> boards8 = boards8ByAdjGaps.get(expansion);
                if (boards8 == null) boards8ByAdjGaps.put(expansion, boards8 = new HashSet<TileSet>());
                boards8.add(expandedBoard8);
            }
        }
        System.err.println(boards8ByAdjGaps.size() + " distinct gap sets in plane next to full one");

        long solutions = 0;
        int progress = 0;
        for (TileSet board : nTiles.get(tilesInPlane2)) {
            // Each board is only expanded once, but we don't keep them all around so we save a lot of memory
            for (TileSet plane2 : expand(board, primsByMainPlane)) {
                for (Map.Entry<Long, Set<TileSet>> plane0 : boards8ByAdjGaps.entrySet()) {
                    solutions += countSolutions(plane0.getKey(), plane0.getValue(), plane2, boards8ByAdjGaps);
                }
            }

            progress++;
            // Progress reports are always good for long processes...
            if (progress % 1000 == 0) System.err.println("Progress: " + progress + "; solutions: " + solutions);
        }
    }

    private static Set<TileSet> expand(TileSet board, Map<Long, Set<Long>> primsByMainPlane) {
        Set<TileSet> bexps = new HashSet<TileSet>();
        bexps.add(new TileSet());
        for (Long tileBase : board) {
            Set<TileSet> nextBexps = new HashSet<TileSet>();
            for (TileSet bexp : bexps) {
                for (Long texp : primsByMainPlane.get(tileBase)) {
                    if ((bexp.sum & texp) == 0) {
                        TileSet nextBexp = new TileSet();
                        nextBexp.addAll(bexp);
                        nextBexp.add(texp);
                        nextBexps.add(nextBexp);
                    }
                }
            }
            bexps = nextBexps;
        }
        return bexps;
    }

    private static int countSolutions(long gaps1, Set<TileSet> planes0, TileSet plane2, Map<Long, Set<TileSet>> boards8ByAdjGaps) {
        int solutions = 0;
        int fitTiles = 0;
        long unfitTiles = 0;
        for (Long tile : plane2) {
            if ((tile & adjPlane) == (tile & gaps1)) fitTiles++;
            else unfitTiles |= tile;
        }

        if (fitTiles >= tilesInPlanes2_3) {
            for (Map.Entry<Long, Set<TileSet>> planes4 : boards8ByAdjGaps.entrySet()) {
                long gaps3 = planes4.getKey();
                if ((unfitTiles & adjPlane) == (unfitTiles & gaps3)) {
                    // The Cartesian product of planes0 and planes4.getValue() are all solutions with the same
                    // plane2
                    for (TileSet plane4 : planes4.getValue()) {
                        for (TileSet plane0 : planes0) {
                            printSolutions(plane0, plane2, unfitTiles, plane4);
                            solutions++;
                        }
                    }
                }
            }
        }

        return solutions;
    }

    private static void printSolutions(TileSet plane0, TileSet plane2, long unfitTiles, TileSet plane4) {
        char[][][] cube = new char[5][5][5];
        // plane0's main plane is 0
        char tileName = 'a';
        for (Long tile : plane0) {
            populatePlane(cube[0], tile & mainPlane, tileName);
            populatePlane(cube[1], tile >> 25, tileName);
            tileName++;
        }
        for (Long tile : plane4) {
            populatePlane(cube[4], tile & mainPlane, tileName);
            populatePlane(cube[3], tile >> 25, tileName);
            tileName++;
        }
        for (Long tile : plane2) {
            populatePlane(cube[2], tile & mainPlane, tileName);
            // The tricky bit: up or down? We look to unfitTiles.
            populatePlane(cube[(unfitTiles & tile) == 0 ? 1 : 3], tile >> 25, tileName);
            tileName++;
        }

        // Print as plane0 plane1 plane2 plane3 plane4
        for (int y = 0; y < 5; y++) {
            for (int z = 0; z < 5; z++) {
                for (int x = 0; x < 5; x++) {
                    System.out.print(cube[z][y][x] == 0 ? '.' : cube[z][y][x]);
                }
                System.out.print(' ');
            }
            System.out.println();
        }
        System.out.println();
        System.out.println();
    }

    private static void populatePlane(char[][] plane, long values, char tile) {
        for (int x = 0; x < 5; x++) {
            for (int y = 0; y < 5; y++) {
                if ((values & (1 << (x + 5*y))) != 0) {
                    if (plane[y][x] != 0) throw new IllegalStateException("Collision!");
                    plane[y][x] = tile;
                }
            }
        }
    }

    static class TileSet extends HashSet<Long> {
        private long sum = 0;

        @Override
        public boolean add(Long val) {
            if ((val & sum) != 0) throw new IllegalArgumentException();
            sum |= val;
            return super.add(val);
        }
    }
}


Determine if 4 points form a square Write a function that takes 4 points on the plane as input and returns true iff the 4 points form a square.  The points will have integral coordinates with absolute values < 1000.

You may use any reasonable representation of the 4 points as input.  The points are not provided in any particular order.

Shortest code wins.

Example squares:

(0,0),(0,1),(1,1),(1,0)    # standard square
(0,0),(2,1),(3,-1),(1,-2)  # non-axis-aligned square
(0,0),(1,1),(0,1),(1,0)    # different order

Example non-squares:

(0,0),(0,2),(3,2),(3,0)  # rectangle
(0,0),(3,4),(8,4),(5,0)  # rhombus
(0,0),(0,0),(1,1),(0,0)  # only 2 distinct points
(0,0),(0,0),(1,0),(0,1)  # only 3 distinct points

You may return either true or false for the degenerate square (0,0),(0,0),(0,0),(0,0)

J, 28 17 25 27

J doesn't really have functions, but here's a monadic verb that takes a vector of points from the complex plane:

4 8 4-:#/.~&(/:~&:|&,&(-/~))

Method is a mix of Michael Spencer (work solely on inter-vertex lengths; but he's currently failing my rhombus2) and Eelvex's (check the sets' sizes) works.  Reading right to left:

-/~ compute all point differences
, flatten
| extract magnitude
/:~ sort up
#/.~ nub and count
4 8 4 -: must have exactly 4 equidistant (at 0), 8 a bit bigger (length 1, sides), 4 bigger yet (length sqrt 2, diagonals)

Demonstration:

   NB. give the verb a name for easier use
   f =: 4 8 4-:#/.~&(/:~&:|&,&(-/~))

   NB. standard square
   f 0 0j1 1j1 1
1

   NB. non-axis-aligned square
   f 0 2j1 3j_1 1j_2
1

   NB. different order
   f 0 1j1 0j1 1
1

   NB. rectangle
   f 0 0j2 3j2 3
0

   NB. rhombus 1
   f 0 3j4 8j4 5
0

   NB. rhombus 2
   f 0 1ad_60 1ad0 1ad60
0

For memory's sake, my previous method (required ordered vertices, but could detect regular polygons of any order):

*./&(={.)&(%1&|.)&(-1&|.)

See history for explanation and demo.  The current method could probably be expanded to other polygons, that 4 8 4 does look a lot like a binomial distribution.