Regex golf and ccTLDs, hooray! Write a regex that only matches valid country code top level domains (ccTLDs). Your regex must match both the domains with the dot and without the dot (it must match tv and .tv). Any domain that is not a ccTLD or does not exist (e.g. .info or .jobs or .xz) must not be matched.

Use Perl, POSIX, PCRE or Python.

For reference, this is the full list of ccTLDs, as of challenge creation:

.ac .ad .ae .af .ag .ai .al .am .ao .aq .ar .as .at .au .aw .ax .az .ba .bb .bd .be .bf .bg .bh .bi .bj .bm .bn .bo .br .bs .bt .bw .by .bz .ca .cc .cd .cf .cg .ch .ci .ck .cl .cm .cn .co .cr .cu .cv .cw .cx .cy .cz .de .dj .dk .dm .do .dz    .ec .ee .eg .er .es .et .eu .fi .fj .fk .fm .fo .fr .ga .gd .ge .gf .gg .gh .gi .gl .gm .gn .gp .gq .gr .gs .gt .gu .gw .gy .hk .hm .hn .hr .ht .hu .id .ie .il .im .in .io .iq .ir .is .it .je .jm .jo .jp .ke .kg .kh .ki .km .kn .kp .kr .kw .ky .kz .la .lb .lc .li .lk .lr .ls .lt .lu .lv .ly .ma .mc .md .me .mg .mh .mk .ml .mm .mn .mo .mp .mq .mr .ms .mt .mu .mv .mw .mx .my .mz .na .nc .ne .nf .ng .ni .nl .no .np .nr .nu .nz .om .pa .pe .pf .pg .ph .pk .pl .pm .pn .pr .ps .pt .pw .py .qa .re .ro .rs .ru .rw .sa .sb .sc .sd .se .sg .sh .si .sk .sl .sm .sn .so .sr .ss .st .sv .sx .sy .sz .tc .td .tf .tg .th .tj .tk .tl .tm .tn .to .tr .tt .tv .tw .tz .ua .ug .uk .us .uy .uz .va .vc .ve .vg .vi .vn .vu .wf .ws .ye .yt .za .zm .zw -- open for registration

.an .bl .bq .bv .eh .gb .mf .sj .su .tp .um -- not open (still must be matched)

^ and $ anchors are not needed.

275 bytes

\.?([cmst][cdghk-orvz]|[agim][delmq-t]|[dft][jkmo]|[acms]x|[bcgkmp][ghmnrwy]|[psu][agksy]|[aen][cegru]|[abcn][fioz]|l[abcikr-vy]|[bdjkprsvy]e|[bcgmnqvz]a|[behpsty]t|[cghmrv]u|[fgksv]i|[gjkmn]p|b[bdjs]|h[kmnr]|[gptw]f|[artz]w|v[cgn]|[joz]m|[ijr]o|[erw]s|[dku]z|[np]l|fr|in|sb)

(277 bytes including ^$.) A Python program was used to autogenerate part of this regular expression. Here is the first version of the program:

def makeregex(list):
  if len(list) == 1:
    return alpha[list[0]]
  regex = "["
  j = list[0]
  while j < 26:
    if j in list:
      if j + 1 in list and j + 2 in list and j + 3 in list:
        regex += alpha[j] + "-"
        while j + 1 in list:
          j += 1
      regex += alpha[j]
    j += 1
  return regex + "]"

def perform(rows, cols):
  replaced = '|'.join([alpha[j] + alpha[k] for j in rows for k in cols if array[j][k] > 0])
  regex = makeregex(rows) + makeregex(cols)
  print regex, 'replaces', replaced, 'saving', len(replaced) - len(regex), 'bytes'
  for j in rows:
    for k in cols:
      if (array[j][k]):
        array[j][k] = -1
      else:
        raise Exception("filling illegal entry")

all = ['ac', 'ad', 'ae', 'af', 'ag', 'ai', 'al', 'am', 'ao', 'aq', 'ar', 'as',
       'at', 'au', 'aw', 'ax', 'az', 'ba', 'bb', 'bd', 'be', 'bf', 'bg', 'bh',
       'bi', 'bj', 'bm', 'bn', 'bo', 'br', 'bs', 'bt', 'bw', 'by', 'bz', 'ca',
       'cc', 'cd', 'cf', 'cg', 'ch', 'ci', 'ck', 'cl', 'cm', 'cn', 'co', 'cr',
       'cu', 'cv', 'cw', 'cx', 'cy', 'cz', 'de', 'dj', 'dk', 'dm', 'do', 'dz',
       'ec', 'ee', 'eg', 'er', 'es', 'et', 'eu', 'fi', 'fj', 'fk', 'fm', 'fo',
       'fr', 'ga', 'gd', 'ge', 'gf', 'gg', 'gh', 'gi', 'gl', 'gm', 'gn', 'gp',
       'gq', 'gr', 'gs', 'gt', 'gu', 'gw', 'gy', 'hk', 'hm', 'hn', 'hr', 'ht',
       'hu', 'id', 'ie', 'il', 'im', 'in', 'io', 'iq', 'ir', 'is', 'it', 'je',
       'jm', 'jo', 'jp', 'ke', 'kg', 'kh', 'ki', 'km', 'kn', 'kp', 'kr', 'kw',
       'ky', 'kz', 'la', 'lb', 'lc', 'li', 'lk', 'lr', 'ls', 'lt', 'lu', 'lv',
       'ly', 'ma', 'mc', 'md', 'me', 'mg', 'mh', 'mk', 'ml', 'mm', 'mn', 'mo',
       'mp', 'mq', 'mr', 'ms', 'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz', 'na',
       'nc', 'ne', 'nf', 'ng', 'ni', 'nl', 'no', 'np', 'nr', 'nu', 'nz', 'om',
       'pa', 'pe', 'pf', 'pg', 'ph', 'pk', 'pl', 'pm', 'pn', 'pr', 'ps', 'pt',
       'pw', 'py', 'qa', 're', 'ro', 'rs', 'ru', 'rw', 'sa', 'sb', 'sc', 'sd',
       'se', 'sg', 'sh', 'si', 'sk', 'sl', 'sm', 'sn', 'so', 'sr', 'ss', 'st',
       'sv', 'sx', 'sy', 'sz', 'tc', 'td', 'tf', 'tg', 'th', 'tj', 'tk', 'tl',
       'tm', 'tn', 'to', 'tr', 'tt', 'tv', 'tw', 'tz', 'ua', 'ug', 'uk', 'us',
       'uy', 'uz', 'va', 'vc', 've', 'vg', 'vi', 'vn', 'vu', 'wf', 'ws', 'ye',
       'yt', 'za', 'zm', 'zw']
alpha = 'abcdefghijklmnopqrstuvwxyz'
array = [[alpha[i] + alpha[j] in all for j in range(26)] for i in range(26)]

#perform([2, 12, 18, 19], [2, 3, 6, 7, 10, 11, 12, 13, 14, 17, 21, 25])
#perform([0, 6, 8, 12], [3, 4, 11, 12, 16, 17, 18, 19])
#perform([3, 5, 19], [9, 10, 12, 14])
#perform([0, 2, 12, 18], [23])

while max(max(row) for row in array) > 0:
  best = 0
  i = 1
  while i < 1 << 26:
    row = [-1 for j in range(26)]
    for j in range(26):
      if (i & 1 << j):
        for k in range(26):
          if array[j][k] == 0:
            row[k] = 0
          elif array[j][k] == 1 and row[k]:
            row[k] = max(row[k], 0) + 1
        if max(row) < 1:
          break;
    if max(row) > 0:
      total = 3 * sum(max(j, 0) for j in row)
      if total > best:
        rows = [j for j in range(26) if i & 1 << j]
        cols = [j for j in range(26) if row[j] > 0]
        total -= len(makeregex(rows)) + len(makeregex(cols)) + 1
        if total > best:
          best = total
          bestrows = rows
          bestcols = cols
      i += 1
    else:
      i += i & -i
  if best:
    perform(bestrows, bestcols)
  else:
    print '|'.join([alpha[j] + alpha[k] for j in range(26) for k in range(26) if array[j][k] > 0])
    break

This 282-byte regex results from its output:

\.?([bgmps][aeghmnrsty]|[cmst][cdghk-orvz]|[acn][cfgiloruz]|[agim][delmq-t]|[bck][ghimnrwyz]|[elm][cr-u]|[dft][jkmo]|[agpt][fltw]|[gnv][aegiu]|[lpu][aksy]|[gjkm][emp]|h[kmnrtu]|b[bdfjo]|r[eosuw]|[ls][biv]|[acms]x|[cmz][amw]|[dey]e|dz|eg|fi|fr|in|io|jo|np|om|qa|ug|uz|vc|vn|wf|ws|yt)

The program can also be seeded by adding calls to perform, so I tried seeding it with [cmst][cdghk-orvz]|[agim][delmq-t]|[dft][jkmo]|[acms]x but that just resulted in a rearranged regex. Obviously this wasn't good enough. The problem seemed to be that I was comparing the performance against a simple alternation. I therefore developed a slower but more accurate scoring function, which works by assuming that all of the remaining matches should be either x[yz] or [xy]z alternations, generating the largest alternations first, and compares the result with and without the trial regex.

def makeregex(list):
  if len(list) == 1:
    return alpha[list[0]]
  regex = "["
  j = list[0]
  while j < 26:
    if j in list:
      if j + 1 in list and j + 2 in list and j + 3 in list:
        regex += alpha[j] + "-"
        while j + 1 in list:
          j += 1
      regex += alpha[j]
    j += 1
  return regex + "]"

def simple(array):
  unused = [[j > 0 for j in row] for row in array]
  regex = ""
  while max(max(row) for row in unused):
    rowcount = [sum(row) for row in unused]
    colcount = [sum(col) for col in zip(*unused)]
    if max(colcount) > max(rowcount):
      colindex = colcount.index(max(colcount))
      col = zip(*unused)[colindex]
      regex += "|" + makeregex([j for j in range(26) if col[j]]) + alpha[colindex]
      for j in range(26):
        unused[j][colindex] = 0
    else:
      rowindex = rowcount.index(max(rowcount))
      row = unused[rowindex]
      regex += "|" + alpha[rowindex] + makeregex([j for j in range(26) if row[j]])
      unused[rowindex] = [0 for j in range(26)]
  return regex

def perform(rows, cols):
  previous = simple(array)[1:].split('|')
  for j in rows:
    for k in cols:
      if (array[j][k]):
        array[j][k] = -1
      else:
        raise Exception("filling illegal entry")
  regex = (makeregex(rows) + makeregex(cols) + simple(array)).split('|')
  replaced = '|'.join(j for j in previous if not j in regex)
  regex = '|'.join(j for j in regex if not j in previous)
  print regex, 'replaces', replaced, 'saving', len(replaced) - len(regex), 'bytes'

all = ['ac', 'ad', 'ae', 'af', 'ag', 'ai', 'al', 'am', 'ao', 'aq', 'ar', 'as',
       'at', 'au', 'aw', 'ax', 'az', 'ba', 'bb', 'bd', 'be', 'bf', 'bg', 'bh',
       'bi', 'bj', 'bm', 'bn', 'bo', 'br', 'bs', 'bt', 'bw', 'by', 'bz', 'ca',
       'cc', 'cd', 'cf', 'cg', 'ch', 'ci', 'ck', 'cl', 'cm', 'cn', 'co', 'cr',
       'cu', 'cv', 'cw', 'cx', 'cy', 'cz', 'de', 'dj', 'dk', 'dm', 'do', 'dz',
       'ec', 'ee', 'eg', 'er', 'es', 'et', 'eu', 'fi', 'fj', 'fk', 'fm', 'fo',
       'fr', 'ga', 'gd', 'ge', 'gf', 'gg', 'gh', 'gi', 'gl', 'gm', 'gn', 'gp',
       'gq', 'gr', 'gs', 'gt', 'gu', 'gw', 'gy', 'hk', 'hm', 'hn', 'hr', 'ht',
       'hu', 'id', 'ie', 'il', 'im', 'in', 'io', 'iq', 'ir', 'is', 'it', 'je',
       'jm', 'jo', 'jp', 'ke', 'kg', 'kh', 'ki', 'km', 'kn', 'kp', 'kr', 'kw',
       'ky', 'kz', 'la', 'lb', 'lc', 'li', 'lk', 'lr', 'ls', 'lt', 'lu', 'lv',
       'ly', 'ma', 'mc', 'md', 'me', 'mg', 'mh', 'mk', 'ml', 'mm', 'mn', 'mo',
       'mp', 'mq', 'mr', 'ms', 'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz', 'na',
       'nc', 'ne', 'nf', 'ng', 'ni', 'nl', 'no', 'np', 'nr', 'nu', 'nz', 'om',
       'pa', 'pe', 'pf', 'pg', 'ph', 'pk', 'pl', 'pm', 'pn', 'pr', 'ps', 'pt',
       'pw', 'py', 'qa', 're', 'ro', 'rs', 'ru', 'rw', 'sa', 'sb', 'sc', 'sd',
       'se', 'sg', 'sh', 'si', 'sk', 'sl', 'sm', 'sn', 'so', 'sr', 'ss', 'st',
       'sv', 'sx', 'sy', 'sz', 'tc', 'td', 'tf', 'tg', 'th', 'tj', 'tk', 'tl',
       'tm', 'tn', 'to', 'tr', 'tt', 'tv', 'tw', 'tz', 'ua', 'ug', 'uk', 'us',
       'uy', 'uz', 'va', 'vc', 've', 'vg', 'vi', 'vn', 'vu', 'wf', 'ws', 'ye',
       'yt', 'za', 'zm', 'zw']
alpha = 'abcdefghijklmnopqrstuvwxyz'
array = [[alpha[i] + alpha[j] in all for j in range(26)] for i in range(26)]

#perform([2, 12, 18, 19], [2, 3, 6, 7, 10, 11, 12, 13, 14, 17, 21, 25])
#perform([0, 6, 8, 12], [3, 4, 11, 12, 16, 17, 18, 19])
#perform([3, 5, 19], [9, 10, 12, 14])
#perform([0, 2, 12, 18], [23])

while max(max(row) for row in array) > 0:
  best = simple(array)[1:]
  bestrows = []
  bestcols = []
  i = 1
  while i < 1 << 26:
    row = [-1 for j in range(26)]
    for j in range(26):
      if (i & 1 << j):
        for k in range(26):
          if array[j][k] == 0:
            row[k] = 0
          elif array[j][k] == 1 and row[k]:
            row[k] = max(row[k], 0) + 1
        if max(row) < 1:
          break;
    if max(row) > 0:
      rows = [j for j in range(26) if i & 1 << j]
      cols = [j for j in range(26) if row[j] > 0]
      unused = [row[:] for row in array]
      for j in rows:
        for k in cols:
          unused[j][k] = 0
      total = makeregex(rows) + makeregex(cols) + simple(unused)
      if len(total) < len(best):
        best = total
        bestrows = rows
        bestcols = cols
      i += 1
    else:
      i += i & -i
  if bestrows:
    perform(bestrows, bestcols)
  else:
    print best
    break

Now without seeding, this actually produces the worse 286-byte regex:

\.?([bgp][ae-hmnrstwy]|[cst][cdghk-orvz]|[nv][acegiu]|m[acdeghk-z]|a[c-gilmoq-uwxz]|k[eghimnprwyz]|l[abcikr-vy]|i[del-oq-t]|s[abeistxy]|c[afiuwxy]|e[cegr-u]|b[bdijoz]|d[ejkmoz]|f[ijkmor]|g[dilpqu]|h[kmnrtu]|n[floprz]|u[agksyz]|r[eosuw]|j[emop]|t[fjtw]|z[amw]|p[kl]|w[fs]|y[et]|om|qa|vn)

When seeded with [cmst][cdghk-orvz] (which I had independently discovered manually before writing the first program) this improves to this 282-byte regex, thus equalling the first program:

\.?([cmst][cdghk-orvz]|[bgmps][aeghmnrsty]|[ag][d-gilmq-uw]|[pt][fkltw]|[acs][cioxz]|[nv][acegiu]|k[eghimnprwyz]|l[abcikr-vy]|i[del-oq-t]|b[bdfijowz]|e[cegr-u]|d[ejkmoz]|f[ijkmor]|h[kmnrtu]|n[floprz]|u[agksyz]|c[afuwy]|m[pquwx]|r[eosuw]|j[emop]|z[amw]|w[fs]|y[et]|gp|om|qa|sb|tj|vn)

After some experimentation I discovered that when seeded with [cmst][cdghk-orvz]|[agim][delmq-t]|[dft][jkmo]|[acms]x (selected from the output of the first version), it results in the given 275-byte regex.

For completeness, I think the best I achieved manually was the following 282-byte regex:

\.?(a[c-gilmoq-uwxz]|b[abd-jostz]|c[afiuwxy]|d[ejkmoz]|e[cegr-u]|f[ijkmor]|g[ad-ilp-u]|h[kmnrtu]|i[del-oq-t]|j[emop]|k[ipz]|l[abcikr-vy]|m[aep-y]|n[acefgilopruz]|om|p[aflst]|qa|r[eosuw]|s[abeistxy]|t[fjtw]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]|[cmst][cdghk-orvz]|[bgkp][eghmnrwy])


Simulate walking with collisions In this challenge, the task is to write a program or function which simulates a number of people walking. Input will be some representation of the people's positions on a 2d grid, and one of four directions (or none) for each.
The movement follows a few rules:

No person can walk into a space occupied by a person who is not moving
No two or more people can walk into the same space (none of them move)
No two adjacent people can swap positions

If a person would not collide with another, they will move one space in the specified direction. You can choose how directions are represented. All coordinates are pairs of integers. No two people will start in the same position.
Test cases:
Inputs are represented as pairs of coordinates ([x, y]), followed by a direction. Outputs are only the resulting coordinates. All of these have four people for simplicity, but inputs can consist of any (non-zero) number of people.
Input 1:
[[[0, 0], +y], [[-1, 0], +x], [[-2, 0], +x], [[1, 0], -x]]

Output 1:
[[0, 1], [-1, 0], [-2, 0], [1, 0]]

Input 2:
[[[0, 0], none], [[0, 1], +y], [[0, 2], +y], [[0, 3], +x]]

Output 2:
[[0, 0], [0, 2], [0, 3], [1, 3]]

Input 3:
[[[0, -1], +y], [[0, -2], +y], [[0, -3], +y], [[1, -2], -x]]

Output 3:
[[0, 0], [0, -1], [0, -3], [1, -2]]

Input 4:
[[[0, 0] +x], [[1, 0], +y], [[1, 1], -x], [[0, 1], -y], [[2, 0], +x]]

Output 4:
[[1, 0], [1, 1], [0, 1], [0, 0], [3, 0]]

Input 5:
[[[0, 0] +x], [[1, 0], +y], [[1, 1], -x], [[0, 1], -y], [[2, 0], -x]]

Output 5:
[[0, 0], [1, 0], [1, 1], [0, 1], [2, 0]]

Input 6:
[[[0, 1], -y], [[1, 1], -x], [[1, 0], +y], [[0, 0] +x], [[2, 0], +x]]

Output 6:
[[0, 0], [0, 1], [1, 1], [1, 0], [3, 0]]

This is code-golf, shortest answer in bytes per language wins!

J, 60 58 50 47 bytes
[:+/(*1,:1-(1<1#.+/=/+/)+{.(~:*[=i.{_,~])+/)^:_

Try it online!
Takes input as a matrix of complex numbers -- starting positions in the 1st row, steps to walk in the 2nd row.
Passes all test cases including those suggested by tsh and the cycle of 4 suggested by xnor.
tldr how
We iteratively adjust the steps to be 0 for impossible moves (same destination (1<1#.+/=/+/) or + swaps {.(~:*[=i.{_,~])+/) until they reach a fixed point ^:_.  Iteration is needed because some steps only become illegal after a walker changes from someone who will move to someone standing still.  There's a chain reaction.
After that iteration, impossible steps will have been converted to 0, and legal steps will remain what they were.
Once that's done, we just add those steps to the starting positions [:+/.


Phone Multi-tap Spelling Inspired by the Google Code Challenge:

The Latin alphabet contains 26 characters and telephones only have ten digits on the keypad. We would like to make it easier to write a message to your friend using a sequence of keypresses to indicate the desired characters. The letters are mapped onto the digits as shown below. To insert the character B for instance, the program would press 22. In order to insert two characters in sequence from the same key, the user must pause before pressing the key a second time. The space character ' ' should be printed to indicate a pause. For example, 2 2 indicates AA whereas 22 indicates B.
Each message will consist of only lowercase characters a-z and space characters ' '. Pressing zero emits a space.

Your challenge is to write the smallest function which takes the input string, and returns the sequence of keypresses necessary to produce the input as string or output it to stdout. The function which is the least amount of bytes wins.
Example Input/Output
phone("hi")
44 444
phone("hello world")
4433555 555666096667775553

Other clarifications

Pauses must only be added when necessary and must be a space ' '.
Each message will consist of only lowercase characters a-z and space characters ' '. Print 0 to signify spaces.
No external libraries.
Only the input string may be passed to your function.
To make other languages competitive, the primary function declaration doesn't count, and nor does importing other standard libraries. #includes, imports, and usings don't count. Everything else does. This does include #defines and helper functions. See rule 2 in this question if you are confused.
Multiple spaces can be denoted as 00 or 0 0 since you don't really have to pause between a space

Ruby, 129 122 115 111 108 107 105

Done with golfing...

Oops, completely forgot to remove unnecessary spaces - fixed...

Saved 2 chars thanks to Peter Taylor.

Online version

def t9(t)
(t.tr(" ",?`).bytes.map{|c|"09998887777666555444333222"[96-c..-1][/(.)\1*/]}*' ').gsub /(\d) (?!\1)/,'\1'
end

Explanation:

space is translated to the char with the ordinal 96

(t.tr(" ",?`).bytes

characters are first mapped to series of numbers:
- a to 2
- b to 22
- d to 3222
- h to 444333222

a regex expression then matches the first group of equal digits

map{|c|"09998887777666555444333222"[96-c..-1][/(.)\1*/]}

the array is joined

*' ')

all spaces in the occurences of "digit space different_digit" are removed

gsub /(\d) (?!\1)/,'\1'


Optimal Alphabet Stepping Given an input string consisting of only letters, return the step-size that results in the minimum amount of steps that are needed to visit all the letters in order over a wrapping alphabet, starting at any letter.

For example, take the word, dog. If we use a step-size of 1, we end up with:

defghijklmnopqrstuvwxyzabcdefg   Alphabet
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
defghijklmnopqrstuvwxyzabcdefg   Visited letters
d          o                 g   Needed letters

For a total of 30 steps.

However, if we use a step-size of 11, we get:

defghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefg
^          ^          ^          ^          ^          ^
d          o          z          k          v          g   Visited letters
d          o                                           g   Needed letters

For a total of 6 steps. This is the minimum amount of steps, so the return result for dog is the step-size; 11.

Test cases:

"dog"      -> 11
"age"      -> 6
"apple"    -> 19
"alphabet" -> 9
"aaaaaaa"  -> 0 for 0 indexed, 26 for 1 indexed
"abcdefga" -> 1 or 9
"aba"      -> Any odd number except for 13
"ppcg"     -> 15
"codegolf" -> 15
"testcase" -> 9
"z"        -> Any number
"joking"   -> 19

Rules

Input will be a non-empty string or array of characters consisting only of the letters a to z (you can choose between uppercase or lowercase)
Output can be 0 indexed (i.e. the range 0-25) or 1 indexed (1-26)
If there's a tie, you can output any step-size or all of them
This is code-golf, so the lowest amount of bytes for each language wins!

Charcoal, 41 bytes

≔ＥＥβＥθ∧μ⌕⭆β§β⁺⌕β§θ⊖μ×κξλ⎇⊕⌊ιΣι⌊ιθＩ⌕θ⌊Φθ⊕ι

Try it online! Link is to verbose version of code. 0-indexed. Explanation:

Ｅβ

Loop over the 26 step sizes. (Actually I loop over the lowercase alphabet here and use the index variable.)

Ｅθ∧μ

Loop over each character of the input after the first.

⭆β§β⁺⌕β§θ⊖μ×κξ

Loop 26 times and generate the string of characters resulting by taking 26 steps at the given step size starting (0-indexed) with the previous character of the input.

⌕...λ

Find the position of the current character of the input in that string, or -1 if not found.

Ｅ...⎇⊕⌊ιΣι⌊ι

Take the sum of all the positions, unless one was not found, in which case use -1.

≔...θ

Save the sums.

⌊Φθ⊕ι

Find the minimum non-negative sum.

Ｉ⌕θ...

Find the first step size with that sum and output it.


Find two integers from an unordered list to sum to the input This is a Google interview question, see here for a youtube link.
The task:
Find 2 integers from an unordered list that sum to a given integer.

Given an unordered list of integers, find 2 integers that sum
to a given value, print these 2 integers, and indicate success (exit 0). They don't need to be any particular numbers (i.e. the first 2 integers summing to the right number), any pair that sums to the value will work.
an integer is positive and greater than zero.
a list of integers can be in any data structure including a file of
integers - one integer per line.
if no integers can be found, indicate a failure (exit 1).
two integers at different positions in list must be returned. (i.e. you can't return the same number from the same position twice)

(Note: in the video, these are not exactly the requirements. The 'interviewer' changed his multiple times.)
eg.
sum2 8 <<EOF
1
7
4
6
5
3
8
2
EOF

Prints 3 and 5 and exit status is 0.
Note that in this 1,7 and 2,6 would also be allowed results.
sum2 8 <<EOF
1
2
3
4

Returns exit status 1 since no possible combo. 4,4 isn't allowed, per rule 5.

Bash, 84 bytes
My implementation of (roughly) Google's engineer's solution but using bash and an input stream - not my solution, so this does not count.
while read V;do((V<$1))&&{ ((T=R[V]))&&echo $T $V&&exit;((R[$1-V]=V));};done;exit 1

Method
while we can read integer V from input stream
if less than target $1 then
if already seen $1-V then print $1-V and V and exit 0
(else) save candidate for input $1-V
exit 1


Golf a number bigger than TREE(3) The function TREE(k) gives the length of the longest sequence of trees T1, T2, ... where each vertex is labelled with one of k colours, the tree Ti has at most i vertices, and no tree is a minor of any tree following it in the sequence.

TREE(1) = 1, with e.g. T1 = (1).

TREE(2) = 3: e.g. T1 = (1); T2 = (2)--(2); T3 = (2).

TREE(3) is a big big number. Even bigger than Graham's number. Your job is to output a number even bigger than it!

This is a code-golf so the goal is to write the shortest program in any language that deterministically outputs a number bigger than or equal to TREE(3) (to the stdout).

You aren't allowed to take input.
Your program must eventually terminate but you can assume the machine has infinite memory.
You might assume your language's number type can hold any finite value but need to explain how this exactly works in your language (ex: does a float have infinite precision?)

Infinities are not allowed as output.
Underflow of a number type throws an exception. It does not wrap around.

Because TREE(3) is such a complex number you can use the fast growing hierarchy approximation fϑ(Ωω ω)+1(3) as the number to beat.
You need to provide an explanation of why your number is so big and an ungolfed version of your code to check if your solution is valid (since there is no computer with enough memory to store TREE(3))

Note: None of the answers currently found here work.

Why is TREE(3) so big?

New Ruby, 135 bytes, >> Hψ(φ3(Ω+1))(9)

where H is the Hardy hierarchy, ψ is an extended version of Madore's OCF (will explain below) and φ is the Veblen function.

Try it online!

f=->a,n,b=a{c,d,e=a;a==c ?a-1:e ?a==a-[0]?[[c,d,f[e,n,b]],d-1,c]:c:[n<1||c==0?n:[f[c||b,n-1]],n,n]};h=[],k=9,k;h=f[h,p(k*=k)]while h!=0

Ungolfed: (using functions, not lambdas)

def f(a,n,b)
  c,d,e = a
  if a == c
    return a-1
  elsif e
    if a == a-[0]
      return [[c,d,f(e,n,b)],d-1,c]
    else
      return c
    end
  else
    x = c || b
    if n < 1 || c == 0
      return [n,n,n]
    else
      return [f(x,n-1,x),n,n]
    end
  end
end

k = 9
h = [[],k,k]
while (h != 0) do
  k *= k
  p k
  h = f(h,k,h)
end

Madore's extended OCF:

And (crudely) Veblen's phi function:

Explanation without ordinals:

f(a,n,b) reduces an array recursively. (if no third argument given, it takes the first argument twice.)
f(k,n,b) = k-1, k is a positive int.
f([c,d,0],n,b) = f([c,0,e],n,b) = c
f([c,d,e],n,b) = [[c,d,f(e,n,b)],d-1,c], d ≠ -1 and c ≠ 0

f([a],0,b) = [0,0,0]
f([0],n,b) = [n,n,n]
f([],n,b) = f([b],n,b)
f([a],n,b) = [f[a,n-1,a],n,n]

My program initiates k = 9, h = [[],9,9]. It then applies k = k*k and h = f(h,k) until h == 0 and outputs k.

Explanation with ordinals:

Ordinals follow the following representation: n, [], [a], [a,b,c], where n,d is a natural number and a,c are all ordinals.
x = Ord(y) if y is the syntactic version of x.
a[n,b] = Ord(f(a,n))
ω = Ord([0]) = Ord(f([a],-1,b))
n = Ord(n)
Ω = Ord([])
ψ'(a) = Ord([a])
ψ'(a)[n] = Ord(f([a],n))
φ(b,c) ≈ Ord([[0],b,c])
a(↓b)c = Ord([a,b,c]) (down-arrows/backwards associative hyper operators I designed just for ordinals)

We follow the following FS for our ordinals:
k[n,b] = k-1, k < ω
ω[n,b] = n(↓n)n
(a(↓b)0)[n,b] = (a(↓0)c)[n,b] = a
(a(↓b)c)[n,b] = (a(↓b)(c[n,b]))(↓b[n,b])a, b ≥ 0 and c > 0.
ψ'(a)[0,b] = 0(↓0)0
ψ'(a)[n,b] = (ψ'(a[n-1,a]))(↓n)ω, a > 0 and n ≥ 0. (also note that we've changed from [n,b] to [n,a].)
Ω[n,b] = ψ'(b)[n,b]

ψ'(ω∙α) ≈ ψ(α), the ordinal collapsing function described in the image above.

My program more or less initiates k = 9 and h = Ω(↑9)9, then applies k ← k² and h ← h[k,h] until h = 1 and returns k.

And so if I did this right, [[],9,9] is way bigger than the Bachmann-Howard ordinal ψ(ΩΩΩ...), which is way bigger than ϑ(Ωωω)+1.

ψ(Ω(↓9)9) > ψ(Ω(↓4)3) > ψ(ΩΩΩ)+1 > ψ(ΩΩωω)+1 > ϑ(Ωωω)+1

And if my analysis is correct, then we should have ψ'(ΩΩ∙x) ~= ψ*(ΩΩ∙x), where ψ* is the normal Madore's psi function. If this holds, then my ordinal is approximately ψ*(φ3(Ω+ω)).

Old Ruby, 309 bytes, Hψ'0(Ω9)(9) (see revision history, besides the new one is way better)


Make StackOverflow Explode (bookmarklet) Sometimes people get frustrated on the StackExchange network (specifically SO).

Your task is to create a bookmarklet that causes StackOverflow to explode/implode/destroy in some fashion.  This will provide a nicer way of dispersing our frustrations.

The Rules:

it must be in the form of a bookmarklet
must work in Chrome and Firefox (latest stable)
jQuery is on the site, so you can use it
no creating a script tag that pulls explosionThisPage.js or similar

Scoring is the number of characters that need to be copied and pasted, except:

-1 if you include an explanation
-5 for each upvote
-10 if you don't use jQuery
-10 if it makes an explosion sound
+9e72 if it actually does harm to the site (F5 should repair the damage)

If the gif's distracting, remove it.

Here's my entry, which I'll call the drunkenator:

javascript:void(setInterval(function(){c='1234567890poiuytrewqasdfghjklmnbvcxzZXCVBNMLKJHGFDSAQWERTYUIOP=)(/&%25$%23"!1';$(':not(iframe,script,style)').contents().each(function(){if(this.nodeType==3&&/\S/.test(this.nodeValue)){a=this.nodeValue.split('');x=0;for(i=0;i<a.length;i++){r=Math.random()*9999;if(r<10){x=1;j=c.indexOf(a[i]);a[i]=(r<4%3F(t=a[i-1],a[i-1]=a[i],t):r<5%3F'':r<6%3Fa[i]+a[i]:j<0%3Fa[i]:c.charAt(j+(r<8%3F1:-1)))}}if(x)this.nodeValue=a.join('')}})},100))

At 474 chars, it's probably not going to win any golf prizes, but I'm hoping to make up for it in upvotes. :)

Here's the same code de-obfuscated:

setInterval(function () {
  var c = '1234567890poiuytrewqasdfghjklmnbvcxzZXCVBNMLKJHGFDSAQWERTYUIOP=)(/&%$#"!1';
  $(':not(iframe,script,style)').contents().each(function () {
    if (this.nodeType==3 && /\S/.test(this.nodeValue)) {
      var a = this.nodeValue.split('');
      var x = 0;
      for (i = 0; i < a.length; i++) {
        r = Math.random() * 9999;
        if (r < 10) {
          x = 1;
          j = c.indexOf(a[i]);
          a[i] = ( r < 4 ? (t = a[i-1], a[i-1] = a[i], t)
                 : r < 5 ? ''
                 : r < 6 ? a[i] + a[i]
                 : j < 0 ? a[i] : c.charAt(j + (r < 8 ? 1 : -1)) );
        }
      }
      if (x) this.nodeValue = a.join('');
    }
  });
}, 100);

What it does is randomly mutate the text on the page, swapping adjacent characters, deleting or duplicating characters or replacing them with ones adjacent to them on the keyboard.  The effect is kind of subtle at first, but leave it running for a while, and the page content will inevitably decay into a mess of drunken typing:

Ps. The code isn't in any way SO-specific, so it'll work on any website that uses jQuery.  Try it on Wikipedia for hilarious results.  The idea is based on something I wrote years ago as a creative interpretation of the "99 bottles of beer" challenge: my version introduced a slowly increasing number of typos into each verse, until the last ones were all but unrecognizable.  If anyone wants to see it, here's the original Perl code.


Longest pristine(ish) codepoint run Your challenge is to create the longest run of characters with incrementing Unicode codepoints in a pristine program as you can. To keep things simple, I'll abridge the definition for this challenge to be "any program which produces no errors but will error if any one character is removed".

Let's define a codepoint run as any contiguous substring of N characters, where 1 <= N <= program length, where the Unicode/UTF-8 codepoints increment by 1 for each character.

For example: abc, <=>, {|, and ƐƑƒƓƔ are all codepoint runs.

Your program (must be a standalone program) doesn't have to be purely a codepoint run. Instead, its score will be the length in characters of the longest codepoint run in its source code. A program dabc's score would be 3.

Note that your program does not need to actually output anything, as long as it does not error.

Compiler warnings do not count as errors
Your program does not need to (but still can) error if more than 1 contiguous character is removed
Your program may take input only if the contents of the input do not affect whether or not the program errors
Any code which is not part of the longest codepoint run is ignored in the scoring
Highest score, as in code golf, is per-language

Python 3, run of 1,114,111

#coding:utf
assert len(open(__file__).read(1061))==1061
"""
�
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂăĄąĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıĲĳĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňŉŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃǄǅǆǇǈǉǊǋǌǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰǱǲǳǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿˀˁ˂˃˄˅ˆˇˈˉˊˋˌˍˎˏːˑ˒˓˔˕˖˗˘˙˚˛˜˝˞˟ˠˡˢˣˤ˥˦˧˨˩˪˫ˬ˭ˮ˯˰˱˲˳˴˵˶˷˸˹˺˻˼˽˾˿̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇͈͉͍͎͓͔͕͖͙͚̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮͯ̕̚͘͜͟͢͝͞͠͡ͅͰͱͲͳʹ͵Ͷͷ͸͹ͺͻͼͽ;Ϳ΀΁΂΃΄΅Ά·ΈΉΊ΋Ό΍ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ΢ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώϏϐϑϒϓϔϕϖϗϘϙϚϛϜϝϞϟϠϡϢϣϤϥϦϧ"""

Try it online!

The triple-quoted contains the entire Unicode range except for the null byte \0 which terminates a program. (Thanks to Chas Brown for suggesting triple-quoting, which allowed 13 more characters.) The TIO link uses a shortened version; assume that the number 1061 is replaced with the code length.

The program opens itself and checks that it has the appropriate length, which guards against any deletion. No one-character deletion can disable this logic in the code. Lowering either the number of characters read or the number checked for equality will make the assertion fail.

I'm not totally sure if all Unicode characters except '\0' are valid in Python code, and I haven't been able to test it. Maybe this is system dependent. Please let me know if this fails at some point.

We can also do this without reading the file:

s="""
�
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂăĄąĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıĲĳĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňŉŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃǄǅǆǇǈǉǊǋǌǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰǱǲǳǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿˀˁ˂˃˄˅ˆˇˈˉˊˋˌˍˎˏːˑ˒˓˔˕˖˗˘˙˚˛˜˝˞˟ˠˡˢˣˤ˥˦˧˨˩˪˫ˬ˭ˮ˯˰˱˲˳˴˵˶˷˸˹˺˻˼˽˾˿̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇͈͉͍͎͓͔͕͖͙͚̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮͯ̕̚͘͜͟͢͝͞͠͡ͅͰͱͲͳʹ͵Ͷͷ͸͹ͺͻͼͽ;Ϳ΀΁΂΃΄΅Ά·ΈΉΊ΋Ό΍ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ΢ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώϏϐϑϒϓϔϕϖϗϘϙϚϛϜϝϞϟϠϡϢϣϤϥϦϧ"""
assert len(s)==999

Try it online!

There isn't a way to delete a character from the assertion line while keeping it syntactically valid and preserving the length number.


How many pages have I torn out? Last month I borrowed a plenty of books from the library. They all were good books, packed with emotions and plot-twists. Unfortunately, at some points I got very angry/sad/disappointed, so I tore some pages out.

Now the library wants to know how many pages I have torn out for each book.

Your goal is to write a program, which takes a sorted, comma-delimited list of numbers as input and prints the minimum and maximum possible page count I could have torn out. Each line represents a book, each number represents a missing page from the book.

Example input:

7,8,100,101,222,223
2,3,88,89,90,103,177
2,3,6,7,10,11
1
1,2

Example output:

4/5
5/6
3/6
1/1
1/2

4/5 means, that I may have torn out either 4 or 5 pages, depending on which side the book's page numbering starts. One could have torn out page 6/7, page 8/9, page 100/101, and page 222/223 (4 pages). Alternatively, one could have torn out page 7/8, page 99/100, page 101/102, page 221/222, and page 223/224 (5 pages).

Remember that a book page always has a front and a back side. Also the page numbering differs from book to book. Some books have even page numbers on the left page; some on the right page. All books are read from left to right.

Shortest code in bytes win. Strict I/O format is not required. Your programs must be able to take one or more books as input. Have fun.

05AB1E, 13 bytes

εD>)ÅÈε€θγg}{

Try it online!

Thanks to Emigna for the heads-up on spec changes.

Explanation

εD>)ÅÈε€θγg}{ – Full program.
ε             – For each book...
 D            – Push two copies of it.
  >           – Increment all the elements of the second copy.
   )          – Wrap the whole stack into a list.
    ÅÈ        – Produces the lists of even natural numbers lower or equal to each element.
      ε       – For each (the modified copies of the book):
       €θ     – Get the last item of each.
         γg   – And split into chunks of equal adjacent elements.
           }  – Close the loop.
            { – Sort the resulting list.


Calculate the p-adic norm of a rational number Calculate the p-adic norm of a rational number

Write a function or a program, that takes 3 integers m,n,p (where p is a positive prime) as input, that outputs the p-adic norm (denoted by |m/n|_p) as a (completely reduced) fraction. Fermat is known to have only very small margins, but what is rather unknown is that he only had a very small computer screen. So try to make the code as short as possible for it to fit on Fermat's screen!

Definition

Given a prime p, every fraction m/n can uniquely be written (ignoring the signs) as (a/b)* p^e such that e is a integer and p divides neither a nor b. The p-adic norm of m/n is p^-e. There is a special case, if the fraction is 0: |0|_p = 0.

The output format must be x/y (e.g. 1/3;  for integers both 10 or equivalently 10/1 is allowed, for negative numbers there must be a leading minus e.g. -1/3)

Details

The program must use stdin/stdout, or just consist of a function that returns the rational number or string. You have to assume that the input m/n is not fully reduced. You can assume that p is a prime. The program has to be able to process integers between -2^28 up to 2^28, and should not take more than 10 seconds.

Built in factorization and prime checking functionalities are not allowed, as well as built in base conversatio, and built in function that calculate the p-adic valuation or norm.

Examples (stolen from wikipedia):

x = m/n = 63/550 = 2^-1 * 3^2 * 5^-2 * 7 * 11^-1
|x|_2 = 2
|x|_3 = 1/9
|x|_5 = 25
|x|_7 = 1/7
|x|_11 = 11
|x|_13 = 1

Interesting trivia

(Not necessary to know/read for this challenge, but perhaps nice to read as a motivation.)

(Please correct me if I use the wrong words, or something else is wrong, I am not used to talking about this in english.)

If you consider the rational numbers as a field, then the p-adic norm induces the p-adic metric d_p(a,b) = |a-b|_p. Then you can complete this field with regard to this metric, that means you can construct a new field where all cauchy sequences converge, which is a nice topological property to have. (Which e.g. the rational numbers do not have, but the reals do.) These p-adic numbers are as you might have guessed, used a lot in number theory.

Another interesting result is Ostrowski's theorem which basically says, any absolut value (as defined below) on the rational numbers is one of the following three:

The trivial: |x|=0 iff x=0, |x|=1 otherwise
The standard (real): |x| = x if x>=0, |x| = -x if x<0
The p-adic (as we defined it).

An absolute value / a metric is just the generalization of what we consider a distance. A absolute value |.| satisfies following conditions:

|x| >= 0  and |x|=0 if x=0
|xy| = |x| |y|
|x+y| <= |x|+|y|

Note that you can easily construct metrics from absolute values and vice versa: |x| := d(0,x) or d(x,y) := |x-y|, so they are almost the same if you can add/substract/multiply (that is in integral domains). You can of course define a metric on more general sets, without this structure.

Julia, 94 80 75 bytes

f(m,n,p)=(k=gcd(m,n)
g(m)=m%p>0?g(m÷p)p:1
m!=0?print(g(n÷k),/,g(m÷k)):0)

Note: using linefeeds in place of semicolons for readability - will work same either way.

This is quite simple - the g(m,n) function uses recursion and remainder (%) to extract the p^n factor from input m, with n=1 as default and then multiplied by p on each step of the recursion, so that the output will be p^n. The code applies that to n/gcd(m,n), and then to m/gcd(m,n) to obtain the appropriate expression. k=gcd(m,n) is used to avoid calculating the gcd(m,n) twice, to save characters. m!=0 is a test to handle the case where x=0.

The output is of the form N/1 or 1/N as appropriate, where N is p^e.


Code Golf: Mix the nuts so that none of the same kind are touching Input:

Input is a randomized array of nuts (in your language), the possible nuts follow. Your program must have a way of representing each kind of nut, such as an integer code. Program must be able to handle any size array of any configuration of nuts.

Possible Nuts:

Kola nut
Macadamia
Mamoncillo
Maya nut
Mongongo
Oak acorns
Ogbono nut
Paradise nut
Pili nut
Pistachio
Walnut

Output:

Output must be the array sorted in such a fashion that there are no adjacent nuts of the
same kind. If this is impossible, the output should be an empty array.

Example Input (simplified):

["walnut", "walnut", "pistachio"]

Example Output:

["walnut", "pistachio", "walnut"]

Solutions may not simply shuffle the array until it becomes unique by chance. The sort employed must be a deterministic one

GolfScript, 42 41 37 38 characters
~.`{\`{=}+%1-,}+$.,)2//zip[]*.2<..&=*p

The code expects input on STDIN and prints result to STDOUT, e.g.:
> ["walnut" "walnut" "walnut" "macadamia" "pistachio"]
["walnut" "macadamia" "walnut" "pistachio" "walnut"]

> ["walnut" "walnut" "walnut" "macadamia" "walnut"]
[]

The script became longer than expected but I suppose there is room for improvement.
Edit: The case of a list with a single item costs me 1 character (the best comparison I could come up with is the same as Peter's).


Shana tova umetuka! (Happy Jewish New Year!) Write the shortest program, in the language of your choice, that takes as input a year on the Hebrew calendar, and outputs the corresponding Gregorian date for Rosh Hashana, in YYYY-MM-DD format.

~$ rh 5771
2010-09-09
~$ rh 5772
2011-09-29
~$ rh 5773
2012-09-17

The input may come from either the command line or from stdin, whichever is more convenient.
You may assume that the year will be between 5600 (1839) and 6000 (2239), inclusive.

Ruby, 192 181 165 characters
require'date'
s=(-6+235*n=gets.to_i)/19*765433+73848;e=s/u=25920
$><<Date.jd(347641+e+([h=s%u/19440,84>>e%7+h&1,v=e%7*(374454>>n%19&1-h&s%u/9923),v,n-5765].count 1))

Input is given as a single number on STDIN.
Edit 1: Several arithmetic transformations saved quite a few characters.
Edit 2: There was some room for improvement.


Average Out Two Lists Average out two lists

Challenge

Given two lists of positive integers, determine whether it is possible to rearrange the elements into two new lists such that the new lists have the same arithmetic mean (average).

Input

The input can be taken through STDIN or as function arguments. Input can be taken as a list, or if your language doesn't support lists (or anything similar such as arrays/dictionaries) then the input can be taken as a comma- or space-delimited string. That is,

"1 4 8 2 5,3 1 5 2 5"

is the same as:

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

All input lists will be the same length.

Output

If you can create two new lists with the same average, your program/function should print or return the mean. If you can't, your program should output a sad face :(.

Note that the rearranged lists with equal means, if they exist, need not has the same length. Any number of swaps can be made to create the new lists.

Examples

1 4 8 2 5,3 1 5 2 5 -> 1 4 8 2 3,5 1 5 2 5 (swapped 3 and 5) -> 3.6
1 3 6 2,16 19 19 14 -> [[1,6,19,14],[3,2,16,19]] -> 10
2 6 2,6 3 5 -> 2 6,2 6 3 5 (moved 2) -> 4
90 80 20 1,40 60 28 18 -> :(

This is code-golf so shortest code in bytes wins. As always, standard loopholes are disallowed.

Pyth, 24 bytes

?}KcsJsQlJmcsdldtPyJK":(

Try it online: Demonstration

Thanks to Dennis for noticing an error and golfing one byte.

Explanation:

?}KcsJsQlJmcsdldtPyJK":(   implicit: Q = evaluated input
      sQ                   all numbers of Q
     J                     save them in J
  KcsJ  lJ                 average of J (sum(J) / len(J))
                           store in K
          m     tPyJ       map each nonempty subset d of J to:
           csdld             average of d
?}                         if K in ^:
                    K        print K
                     ":(   else print sad-face


Counting symmetric grid chains Notation and definitions

Let \$[n] = \{1, 2, ..., n\}\$ denote the set of the first \$n\$ positive integers.

A polygonal chain is a collection of connected line segments.

The corner set of a polygonal chain is a collection of points which are the endpoints of one or more of the line segments of the chain.

Challenge

The goal of this challenge is to write a program that takes two integers, \$n\$ and \$m\$ and computes the number of non-self-intersecting polygonal chains with corner set in \$[n] \times [m]\$ that hit every point in \$[n] \times [m]\$ and are stable under \$180^\circ\$ rotation. You should count these shapes up to the symmetries of the rectangle or square.

Note: In particular, a polygon is considered to be self-intersecting.

Example

For example, for \$n=m=3\$, there are six polygonal chains that hit all nine points in \$[3] \times [3]\$ and are the same after a half-turn:

Table of small values

 n | m | f(n,m)
---+---+-------
 1 | 2 | 1
 1 | 3 | 1
 2 | 1 | 1
 2 | 2 | 1
 2 | 3 | 5
 2 | 4 | 11
 2 | 5 | 23
 3 | 1 | 1
 3 | 2 | 5
 3 | 3 | 6
 3 | 4 | 82

Scoring

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

Python 3 + SymPy, 480 455 452 bytes

lambda w,h:len({min(I(D(H(V(x)))for x in o)for H,V,D in Q((lambda p:(w+~p[0],p[1]),I),(lambda p:(p[0],h+~p[1]),I),(lambda p:p[::-1],I)))for o in permutations(Q(range(w),range(h)))for s in[[*zip(o,o[1:])]]if any(x-~X-w|y+Y-h+1for(x,y),(X,Y)in zip(o,o[::-1]))+any(gcd(x-X,y-Y)>1for(x,y),(X,Y)in s)+any((len({*u,*v})>3)*intersection(S(*u),S(*v))for u,v in Q(s,s))<1})
from math import*
from sympy import*
from itertools import*
Q=product
S=Segment
I=tuple

Try it online!

Inlined version of the previous answer below. -3 bytes thanks to Kevin Cruijssen's tip.

Python 3 + SymPy, 480 bytes

from math import*
from sympy import*
from itertools import*
Q=product
S=Segment
I=tuple
def f(w,h):
 a={1}
 for o in permutations(Q(range(w),range(h))):
  s=[*zip(o,o[1:])]
  if any(x+X-w+1|y+Y-h+1for(x,y),(X,Y)in zip(o,o[::-1]))+any(gcd(x-X,y-Y)>1for(x,y),(X,Y)in s)+any((len({*u,*v})>3)*intersection(S(*u),S(*v))for u,v in Q(s,s))<1:a.add(min(I(D(H(V(x)))for x in o)for H,V,D in Q((lambda p:(w-1-p[0],p[1]),I),(lambda p:(p[0],h-1-p[1]),I),(lambda p:p[::-1],I))))
 return~-len(a)

Try it online!

The golfed version takes too long to check the nontrivial answers. The version below has a shortcut in the conditional, so you can check that the results up to (2,4) are correct.

Python 3 + SymPy, 483 bytes

from math import*
from sympy import*
from itertools import*
Q=product
S=Segment
I=tuple
def f(w,h):
 a={1}
 for o in permutations(Q(range(w),range(h))):
  s=[*zip(o,o[1:])]
  if(any(x+X-w+1|y+Y-h+1for(x,y),(X,Y)in zip(o,o[::-1]))or any(gcd(x-X,y-Y)>1for(x,y),(X,Y)in s)+any((len({*u,*v})>3)*intersection(S(*u),S(*v))for u,v in Q(s,s)))<1:a.add(min(I(D(H(V(x)))for x in o)for H,V,D in Q((lambda p:(w-1-p[0],p[1]),I),(lambda p:(p[0],h-1-p[1]),I),(lambda p:p[::-1],I))))
 return~-len(a)

Try it online!

Ungolfed, with comments

from math import*
from sympy import*
from itertools import*
def pass_point(p1,p2): # test if the segment passes through another point
 return gcd(p1[0]-p2[0],p1[1]-p2[1]) > 1
def f(w,h):
 pts = [(i,j) for i in range(w) for j in range(h)]
 ans = set()
 for orders in permutations(pts):
  # test if the ordering has 180 degrees rotational symmetry
  if any(x1+x2!=w-1or y1+y2!=h-1for (x1,y1),(x2,y2) in zip(orders, orders[::-1])):continue
  segments = [*zip(orders, orders[1:])]
  # test if a segment passes through another point or two segments intersect
  if any(pass_point(*p)for p in segments)+any(len({*s1,*s2})==4and intersection(Segment(*s1),Segment(*s2))for s1 in segments for s2 in segments):continue
  # take minimum of 8 possible rotations/reflections
  flipH = lambda p:(w-1-p[0],p[1]); flipV = lambda p:(p[0],h-1-p[1]); flipD = lambda p:p[::-1]; nop = lambda p:p
  flipmin = min(tuple(map(lambda o:d(h(v(o))),orders))for h in (flipH,nop)for v in (flipV,nop) for d in (flipD, nop))
  ans.add(flipmin)
 print(len(ans))

Try it online!

SymPy has Geometry module that includes an intersection checker intersection that works for line segment Segment objects. This is much shorter than rolling a hand-written intersection checker based on coordinates. The intersection of two Segments is either an empty array (if they don't intersect) or an array that contains a single object (either Point or Segment, depending on the input).


Implement Two-Layer Perceptron Algorithm Train a two-layer perceptron.  You will find the Wikipedia article and these lecture slides useful.

Use a sigmoid activation function for both the hidden and output layers, $$\sigma(x) = \frac{1}{1 + e^{-x}}$$

Your function should take in a list or array of input/output pairs and an integer specifying how many training passes through the input set to make.  Both the input and output will be vectors of any convenient representation in your language.  You should output or otherwise initialize a classifier function or object.

Initialize the weights randomly and to prevent overflow/underflow, normalize the weight vectors after each update.

You should handle input data vectors up to 1000 dimensions and at least 10 output dimensions.  The classifier function should return a vector of the activation levels of each of the outputs.

You may assume access to implementations of all of the BLAS routines.

The MNIST database has a very large training and test set you might find useful for testing purposes.

EDIT: Example dataset.

Input and output vectors (input).

Input  Output
[0,0]   [0]
[0,1]   [1]
[1,0]   [1]
[1,1]   [0]

Your program should produce a classifier that takes in a vector of two elements and returns a vector of one element that has similar behavior as the input.

I'm going to cheat here, hence community wiki: instead of logistic sigmoid, I'll use the hyperbolic tangent and instead of backprop, I'll use ELM to train the perceptron. Here's the version for XOR, in Python, using BLAS via SciPy.

import numpy as np
from scipy.linalg import pinv2

n_hidden = 10  # hyperparameter

# Training set
X_train = np.array([[0,0], [0,1], [1,0], [1,1]])
y_train = [0, 1, 1, 0]

# set hidden layer parameters randomly
w = np.random.randn(X_train.shape[1], n_hidden)
b = np.random.randn(n_hidden)

# compute hidden layer activation
H = np.tanh(np.dot(X_train, w) + b)

# fit output layer parameters
beta = np.dot(pinv2(H), np.atleast_2d(y_train).T)

# prediction and evaluation
pred_train = (np.dot(H, beta) > .5).ravel()
print "Training set accuracy:", np.mean(pred_train == y_train)

I previously published a digits classification script using this algorithm. After removing comments, this is 11 lines of code @ 425 characters.


Not-endless Recursion without a base case Write a recursive function/program, to calculate either the Factorial or the Fibonacci number of a given non-negative integer, without explicitly implementing the base case(s).

Your program/function must return/output the correct value in a reasonable time.

You cannot

Use if statement anywhere in your program/function, nor switch
nor short-if-syntax (?:). Not even loops. Basically all
control-flow statements are forbidden.
Use try, catch or exceptions of any kind.
Terminate the program (anything like exit(1)).
Use external sources (file, web, etc.)
Avoid recursion and return the proper value otherwise. (Your function must be recursive).
Use any of the standard loopholes.

You can

Use polymorphism, create threads, wrap the Integer type with your own class, or use any other mechanism your language or runtime has. (I can think of a solution that uses the lazy-evaluation, for instance). The function/program can be written as more than one function, using Mutual Recursion, if it helps you.

Please provide a short explanation of what you did.

Be creative! The winning answer is the one with the most upvotes by 2014-06-23 (a week from today).

EDIT:

Some clarifications:

Using Pattern Matching in Functional Programming Languages is OK since it's considered as Polymorphism. The solution should be trivial though, so I guess it won't have the chance to win, since it is a popularity-contest. It is still a legitimate answer.

Although some may say it's flow control in disguise, using lazy evaluation, (or short circuit evaluation) is allowed as well.

C - factorial
simple as that
int not_factorial(int n){return 1;}
int factorial(int n)
{
    int (*maybe_factorial[])(int) = {factorial, not_factorial};
    return n*maybe_factorial[!(n-1)](n-1);
}

the function factorial is almost like a basic recursive approach but not_factorial only returns 1.If I create an array of function pointers
(0: fac, 1: not_fac), then I can control which one should be executed at the next call:
maybe_factorial[0](n-1) calls factorial
maybe_factorial[1](n-1) calls not_factorial.
!(n-1) means if n > 1 return 0 else return 1


sed 4.2.2, Score 25
26 bytes, but scoring ¯ as 1, as per note in challenge.
s|1(1*)1|/\1\\|g
y/01/_¯/

Try it online!


Couch 2048: How much more till 2048? I have just tried a game called Couch 2048.
(Note: You should have a look to better understand this question.)
Since it wasn't very exciting for me, I've been asking myself 'How much more till 2048!?'
That inspired me to post a challenge, because calculating this in not as easy as I thought.

Your goal:
Given a list of balls on the sofa, you have to output how many balls with a value of 2 have to fall from the sky so that one can win the game (by reaching the 2048 ball).

Assume the input is valid.
Assume the player won't drop any balls.
Assume the balls which fall from the sky always have a value of 2, as I've said.
Valid output examples: 3, "4", [5], ["6"]

Edit:
I should clarify something:
 - You have to print the smallest amount of 2s needed.

Test cases:
[2048] -> 0 You've already won
[1024,1024] -> 0 You don't need any more balls to win
[1024,512,256,128,64,32,16,8,4,2] -> 1 One ball required to 'activate the chain'
[512] -> 768
[512,2] -> 767
[4,16,64] -> 982

Notes:
I'm not a native speaker - Tell me if you spotted a typo or some non-grammatical text.
If something's unclear, ask in comments.

Java 8, 17 bytes

s->1024-s.sum()/2

Port of @LuisFelipeDeJesusMunoz' JavaScript answer.
Try it online.
Explanation:
s->           // Method with IntStream parameter and int return-type
  1024-       //  Return 1024, minus:
   s.sum()    //   The sum of the input-IntStream
          /2  //   Divided by 2


Print the Russian Cyrillic alphabet Apparently, we really like printing the alphabet in different languages.

How about the Russian Cyrillic alphabet?

Print/output/return this exact text (trailing whitespace is permitted)

АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя

This is the Russian Cyrillic alphabet with upper and lower case interleaved (eg AaBbCc...)

This is code-golf so crunch those bytes folks!

Рапира (Rapira), 172 142 bytes
ВЫВОД: "АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя"

Try it online!
Just for fun, given the challenge. It may not be golfed; I'm not really familiar with the language.


So sayeth the Shepherd I'm tired, but I can't seem to fall asleep. Help me count sheep.

Given an input N (positive integer), make N sheep jump over an ascii fence, like the sample below. Only one frame should be displayed at once:

o |-|
──|-|──  0

 o|-|
──|-|──  0

   o
  |-|
──|-|──  0

  |-|o
──|-|──  0

  |-| o
──|-|──  0

o |-|
──|-|──  1

 o|-|
──|-|──  1

   o
  |-|
──|-|──  1

Count should be kept at the lower right side of the 'ground'. Trailing and leading whitespace and newlines are allowed. If your language of choice has difficulty clearing the screen for each frame you can add sufficient newlines to clear the screen - please state how many lines you add for this in your answer. The program should terminate when the N'th sheep is on the fifth floortile.

I need to get up early tomorrow, so shortest code in bytes wins. Please submit a function or complete program. Standard loopholes apply.

MATL, 60 56 53 bytes
:"@qXJx[HKCbO]"7Z"'  |-|  'v'o'@('--|-|--  '  JVhXxXD

The animation with the above code runs very fast. The following version includes a pause to make the animation slower and thus easier to see (not required by the challenge), at the cost of 4 more bytes:
:"@qXJx[HKCbO]"7Z"'  |-|  'v'o'@('--|-|--  '  JVhXxXD.2Y.

Try it at MATL Online! The interpreter is a beta; refresh the page if it doesn't work.
Or see a recording from the offline compiler:

Explanation
:"              % Input N implicitly. Repeat N times
  @q            %   Push iteration index minus 1, that is, from 0 to N-1. This
                %   are the numbers of sheep
  XJx           %   Copy into clipboard J and delete
  [HKCbO]       %   Push array [2 4 7 -2 0]
  "             %   For each value in that array. This loops generates the 5
                %   frames for each number of sheep
    7Z"         %     Push string of 7 spaces
    '  |-|  '   %     Push this string
    v           %     Concatenate vertically. This gives a 2x7 char array
                %     with the upper part of the frame, except the 'o',
                %     which will be now placed in a varying position
    'o'         %     Push string 'o'
    @           %     Push loop variable, that is, 2, 4, 7, -2 or 0
    (           %     Write 'o' into that position of the 2x7 char array.
                %     The position is interpreated linearly, that is, a single
                %     number is used as index into the 2D array in column-major
                %     order (down, then across). So index 2 is lower-left corner,
                %     index 4 is to the right of that etc. Indexing is
                %     semi-modular (modular for non-positive values). So 0 is
                %     the lower-right corner, and -2 is to the left of that
    '--|-|--  ' %     Push this string
    JV          %     Push current number of sheep converted to string
    h           %     Concatenate horizontally
    Xx          %     Clear screen
    XD          %     Display all stack contents
    .2Y.        %     Pause for 0.2 seconds (optional)
                %   End implicitly
                % End implicitly


Generate a looping array Introduction

A pointer array is an array L of nonzero integers where 0 ≤ L[i]+i < len(L) holds for all indices i (assuming 0-based indexing).
We say that the index i points to the index L[i]+i.
A pointer array is a loop if the indices form a single cycle of length len(L).
Here are some examples:

[1,2,-1,3] is not a pointer array, because the 3 does not point to an index.
[1,2,-1,-3] is a pointer array, but not a loop, because no index points to the -1.
[2,2,-2,-2] is a pointer array, but not a loop, because the indices form two cycles.
[2,2,-1,-3] is a loop.

Input

Your input is a non-empty list of nonzero integers, in any reasonable format.
It may be unsorted and/or contain duplicates.

Output

Your output shall be a loop that contains all the integers in the input list (and possibly other integers too), counting multiplicities.
They need not occur in the same order as in the input, and the output need not be minimal in any sense.

Example

For the input [2,-4,2], an acceptable output would be [2,2,-1,1,-4].

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Including a couple of example inputs and outputs in your answer is appreciated.

Test cases

These are given in the format input -> some possible output(s).

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


Merge Two Paragraphs with Removing Duplicated Lines Challenge
The goal of this challenge is to make a function that takes two paragraphs and output a concatenated result with removing the duplicated overlapped lines due to redundancy (but a single copy of the part of overlapped lines should be kept to avoid information loss). Each input paragraph is with the follows specifications.

The leading/trailing spaces in each line have been removed.

No empty line.

The output merged paragraph follows the rules as below.

Input paragraph 2 is concatenated after input paragraph 1

If the line(s) from the start of the input paragraph 2 is / are sequenced same (overlapped) as the end of input paragraph 1, just keep single copy of the sequenced duplicated lines.

The definition of duplicated lines here:

The content in two line should be totally the same, no “partial overlapping” cases need to be considered.

The content sequence in two blocks of lines should be totally the same.

Example Input and Output

Inputs
Input paragraph 1 example:
Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers.
It's built and run by you as part of the Stack Exchange network of Q&A sites.
With your help, we're working together to build a library of programming puzzles and their solutions.
We're a little bit different from other sites. Here's how:
Ask questions, get answers, no distractions
This site is all about getting answers. It's not a discussion forum. There's no chit-chat.

Input paragraph 2 example:
We're a little bit different from other sites. Here's how:
Ask questions, get answers, no distractions
This site is all about getting answers. It's not a discussion forum. There's no chit-chat.
Good answers are voted up and rise to the top.
The best answers show up first so that they are always easy to find.
The person who asked can mark one answer as "accepted".
Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked.
Get answers to practical, detailed questions
Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do.
Not all questions work well in our format. Avoid questions that are primarily opinion-based, or that are likely to generate discussion rather than answers.

Expected Output

The two block of text are the same, so keep single overlapped part after merging.

Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers.
It's built and run by you as part of the Stack Exchange network of Q&A sites.
With your help, we're working together to build a library of programming puzzles and their solutions.
We're a little bit different from other sites. Here's how:
Ask questions, get answers, no distractions
This site is all about getting answers. It's not a discussion forum. There's no chit-chat.
Good answers are voted up and rise to the top.
The best answers show up first so that they are always easy to find.
The person who asked can mark one answer as "accepted".
Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked.
Get answers to practical, detailed questions
Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do.
Not all questions work well in our format. Avoid questions that are primarily opinion-based, or that are likely to generate discussion rather than answers.

Rules of Challenge
This is code-golf. The answer with the least bytes wins.

Python 3.8 (pre-release), 104 bytes

def o(a,b,i=None):
 while(i:=a[:i].rfind(b[0]))+1:
  if b.find(a[i:])==0:return a[:i]+b
 return a+'\n'+b

Try it online!
I've come up with this as my first ever Code Golf challenge. Defines function o (short for overlay) which returns string a overlayed with string b, or their concatenation if there is no overlap.
It repetitively searches backwards in a for the first letter of b and, if a match is found, compares from that point on in a to the beginning of b until an overlap is found or a has been fully scanned.


Integer Keys and Duplicates Given a non-empty list/vector of positive integers, write a function to check the following conditions in as few bytes as possible.

Take the first integer (the key, or k1) and check that the next k1 values have no duplicate values, excluding instances of k1.
Take the last integer (the second key, or k2) and check that the k2 values before k2 have no duplicate values, excluding instances of k2.

Note that both keys, k1 and k2, are elements of the list/vector as either key could contain the other.

Also, k1 and/or k2 can be greater than the number of integers within the list, which means you should check every element of the list except for instances of the given key for duplicates.

If both steps return True, return True, else, return False.

NOTE: It should be rather intuitive that searching for duplicates within the first k1+1 elements excluding instances of k1 will exclude the first element, or k1. Some answers I've seen "pop" k1 off the list and do the test on the next k1 elements. Either method yields the same results. This is also true for k2 and it's test.

Test Cases

[5,1,2,5,3,4,3] is TRUE because [k1=5][1,2,5,3,4] has no duplicates, nor does [5,3,4][k2=3] have any duplicates, excluding instances of k3.

[6,9,12,15,18,19,8,8,3] is FALSE because [k1=6][9,12,15,18,19,8] has no duplicates while [19,8,8][k2=3] has a duplicate.

[100,100,100,100,101,102,3] is TRUE because [k1=100][100,100,100,101,102,3] has no duplicates, and [100,101,102][k2=3] has no duplicates.

[100,100,100,100,101,102,4] is FALSE. [k1=100][100,100,100,101,102,4] has no duplicates, but [100,100,101,102][k2=4] has duplicates.

[6,6,6,6,6,6,6,3,3,3,3] is TRUE. [k1=6][6,6,6,6,6,6] has no duplicates, excluding instances of k1, and [3,3,3][k2=3] has no duplicates, excluding instances of k2.

[1,2] is TRUE (clearly)

[1] is TRUE (clearly)

JavaScript (ES6),  88 75 71  69 bytes

a=>(g=_=>!a.reverse().some(o=(v,i,[k])=>v-k&&o[v]&(o[v]=i<=k)))()&g()

Try it online!
Commented
The function \$g\$ reverses the input array and performs the test with the resulting leading key.
g= _ =>               // g takes no explicit input
  !a.reverse()        // reverse the input array a[]
  .some(o =           // we use the object o to store encountered values
    (v, i,            // for each value v at position i in a[],
           [k]) =>    // with k = leading value:
      v - k &&        //   abort if v is equal to the key
      o[v] &          //   otherwise, test whether o[v] is already set
      (o[v] = i <= k) //   and i is less than or equal to the key,
                      //   in which case o[v] is set
  )                   // end of some()

The main function simply invokes \$g\$ twice.
a => g() & g()


The Rod Cutting problem Given a rod of length n inches and a list of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6)
length   | 1   2   3   4   5   6   7   8
-------------------------------------------
price    | 1   5   8   9  10  17  17  20

And if the prices are as following, then the maximum obtainable value is 24 (by cutting in eight pieces of length 1)
length   | 1   2   3   4   5   6   7   8
--------------------------------------------
price    | 3   5   8   9  10  17  17  20

The input will be given in this form:
The prices will be in ascending order, index starting at 1 to n separated by a space.
{price of length 1} {price of length 2}.... {price of length N}
The output should be the maximum Obtainable Value
{maxVal}
a Non-Golfed solution to this, in Python is:
INT_MIN = -32767
def cutRod(price, n):
    val = [0 for x in range(n+1)]
    val[0] = 0
    for i in range(1, n+1):
        max_val = INT_MIN
        for j in range(i):
             max_val = max(max_val, price[j] + val[i-j-1])
        val[i] = max_val

    return val[n]

arr = [1,2,3,4,5,6,7,8,9,10]
size = len(arr)
print(cutRod(arr, size))

Test cases:
|                                      Input                                     | Output |
|:------------------------------------------------------------------------------:|:------:|
|                              `1 5 8 9 10 17 17 20`                             |  `22`  |
|                                `1 3 2 5 6 7 4 8`                               |  `12`  |
|                     `5 6 3 2 4 6 8 7 3 4 6 2 12 4 5 7 4 3`                     |  `90`  |
| `23 2 3 45 34 23 3143 13 13 213 1321 3123 12 312 312 31 3 213 432 41 3 123 43` | `9475` |

Jelly, 7 bytes
LŒṗịµ§Ṁ
L        length
 Œṗ      integer partitions
   ị     index
     §Ṁ  sum each and take the maximum

My first jelly answer, so there can probably be improvements made.
Try it online!


(A[l(t[e(r)n]e)s]t) a string! Alternesting, is the act of taking a string and nesting it in alternating brackets. Here is how you alternest a string.

For a string of length N, take the center N characters, and surround them in parenthesis. So if our string was Hello world! (12 characters), we'll end up with

(Hello world!)

Then, take the remaining center n-2 characters, and surround them in square brackets. In this case, the center 10 characters are ello world, so the next iteration is:

(H[ello world]!)

As long as there are more than two characters left in the middle of the string, repeat the last two steps, alternating between () and []. Here are the last steps:

(Hello world!)
(H[ello world]!)
(H[e(llo worl)d]!)
(H[e(l[l(o[ w]o)r]l)d]!)

Since there are only two characters left in the middle on the last iteration, we stop. Our final string is

(H[e(l[l(o[ w]o)r]l)d]!)

Note how there are two characters in the middle brackets. This happens when the input is an even length. If the input was an odd length (for example, Hello, world! with a comma added), we would have only one character in the middle:

(H[e(l[l(o[,( )w]o)r]l)d]!)

For today's challenge, you must write a program or function that takes a string as input, and alternests it, outputting the new string. You can take input and output in any reasonable format you like. The input will always be at least one character long, and will only contain printable ASCII. You can also assume that the input will not contain any parenthesis or square brackets. For traditional languages, this shouldn't matter too much, but it might make it easier for some esoteric languages.

As usual, this is a code-golf competition, so try to make the shortest possible answer in the language of your choice. Have fun!

Test IO

#Input                      #Output

"Alternesting is fun!"  --> (A[l(t[e(r[n(e[s(t[in]g) ]i)s] )f]u)n]!)
"PPCG"                  --> (P[PC]G)
"Code-golf"             --> (C[o(d[e(-)g]o)l]f)
"4 8 15 16 23 42"       --> (4[ (8[ (1[5( [1]6) ]2)3] )4]2)
"a"                     --> (a)
"ab"                    --> (ab)
"abc"                   --> (a[b]c)

Python 3, 70 69 65 bytes

-1 byte thanks to @Uriel
-4 bytes thanks to @xnor

f=lambda s,b=0:s and'(['[b]+s[0]+f(s[1:-1],~b)+s[1:][-1:]+')]'[b]

Try it online!


More coding expressions like while(!(succeed = try()))? I am looking for either suggestions or examples of more famous sayings written in code! If you have a website or database of them, please link that below your favorite one!
Examples:

while(!(succeed = try()))

if(lifegivesyou == lemons) {makelemonade();)

How about:

~wish&~want;

or

Penny.Earned = Penny.Save();


Visualise long multiplication with ASCII art The challenge

Write a program that takes two integers from standard input, separated by a comma, and then prints a visualisation of long multiplication of those two integers to standard output.

Eg:

Input

14, 11

Program output

     14
    x11
   _____
     14
    14
  ______
    154

Input

-7, 20

Program output

     -7
    x20
   _____
     00
    14
   _____
   -140

Assume always correct inputs and numbers in the range [-999, 999]

Winning criteria

Shortest code wins!

Mathematica 213 217 197 193 186 184 193 184 177
Code
a_~g~b_ :=
With[{e = IntegerDigits@b}, Column[Flatten@{a, UnderBar["x " <> IntegerString[b]],
Table[Row @@ {PadRight[{a Reverse[e][[i]]}, i, " "]}, {i, Length@e}], OverBar[a b]},
Alignment -> Right]]

Usage
g[845, 921]


Implement atoi function You already know that the atoi function of stdlib.h converts a string to an integer.

atoi

(copied from here)

 int atoi (const char * str);

  Convert string to integer

  Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.

Example

#include <stdio.h>      /* printf, fgets */
#include <stdlib.h>     /* atoi */

int main ()
{
  int i;
  char buffer[256];
  printf ("Enter a number: ");
  fgets (buffer, 256, stdin);
  i = atoi (buffer);
  printf ("The value entered is %d. Its double is %d.\n",i,i*2);
  return 0;
}

Your task is to implement it, making sure it works for all negative integers in the range, and try to make the code as small as you can.

Python 3 - multicore or go home

# The venerable C atoi function hails from a more innocent time. These days,
# we have multicore processors and programs must adapt or be left behind.
import re
import multiprocessing as mp

def atoi(a):
    m = re.match(r"^\s*(-?)(\d+).*$", a)
    if m is None:
        raise ValueError(a)
    sign = -(m.group(1) == "-") * 2 + 1
    places = enumerate(reversed(bytes(m.group(2), "ascii")))
    with mp.Pool(processes=mp.cpu_count()) as pool:
        return sign * sum(pool.map(_digit, places))

def _digit(t):
    i, b = t
    return 10 ** i * (b - 48)

if __name__ == '__main__':
    import unittest
    error_case = unittest.TestCase().assertRaises(ValueError)
    assert atoi(" -4555553") == -4555553
    assert atoi("1") == 1
    assert atoi("    0") == 0
    assert atoi("100asdf") == 100
    assert atoi("-5") == -5
    assert atoi("1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz") == 1
    assert atoi("1.2") == 1
    with error_case:
        atoi("foobar")
    with error_case:
        atoi("a1234")

Now I have 2 + cpu_count() problems.


Make an error quine! Your challenge: write a "program", for a language of your choice, that causes the compiler/interpreter/runtime to produce error output when compiling/running your program which is identical to your program's source code.

Rules:

Your program may be specific to a particular version or implementation of your language's compiler/interpreter/runtime environment. If so, please specify the particulars.
Only standard compiler/interpreter/runtime options are permitted. You cannot pass some weird flag to your compiler to get a specific result.
The program does not need to be syntactically or semantically valid, but I may give a bounty to the best syntactically valid submission.
The program must not produce any output of its own (e.g. by calling a print or output function). All output generated upon attempting to compile/run the program must originate from the compiler/interpreter/runtime.
The complete output of the compiler/interpreter/runtime must be exactly identical to your program source code.
The compiler/interpreter/runtime must generate at least one error message when invoked with your program.

This is a popularity contest. Most creative answer, as determined by upvotes, wins. If you can give a good case for using a standard loophole, you may do so.

Windows Command Prompt

& was unexpected at this time.


Chess Analysis with Limited Information In this challenge, you are given a limited amount of information about a particular game of chess, and you need to predict who won the game.
You are given two sets of data:

Piece counts (What pieces are still alive)
Board colors (The color of pieces on the board)

More importantly, you don't know where the pieces are located. You need to determine who you think will win.
Games are selected from all events listed on PGNMentor from 2010 to now.  I've selected 10% of all of the board positions from each game that ends in a win or a loss.  Board positions will always be at least 30 moves into the game.  The test cases can be found here.  (White wins are listed first, followed by black wins)
Input
The piece count will be a string consisting of a character for each piece: king, queen, rook, knight, bishop, or pawn.  Lowercase means black, uppercase is white.  The board will be a string of 64 characters (8 rows by 8 columns). B represents a black piece, W represents a white piece, and . represents an empty spot.  Sample:
W..WB......W.BB....W..B..W.WWBBB..W...B....W..BBWWW...BB.W....B.,BBKPPPPPPPQRRbbkpppppppqrr

would represent the following board
...B.BB.
.BBBBBBB
.B.B....
B..W....
WWWW.W..
....W.W.
...W..WW
W.....W.

and where both colors have 2 Bishops, 1 King, 7 Pawns, 1 Queen, 2 Rooks
Output
You need to return a floating-point number between 0 and 1 (inclusive) to determine how likely it is that white wins.  Sample:
0.3     (30% chance that white wins)

More details:

Each test case is worth 1 point. Your score will be 1 - (1-Output)^2 if white wins, or 1 - (Output)^2 if black wins.
Your final score will be the sum across all test cases.
If I feel that submissions are hardcoding the input, I reserve the right to change the test cases.  (If I do change them, they will have the SHA-256 hash 893be4425529f40bb9a0a7632f7a268a087ea00b0eb68293d6c599c6c671cdee)
Your program must run test cases independently.  No saving information from one test case to the next.
If you are using machine learning, I highly recommend training on the first 80% of the data, and testing using the remaining 20%.  (Or whatever percentages you use). I use the games multiple times in the data, but I put the same games together sequentially.
UPDATE: I've added over a million test cases for testing and learning purposes.  They are split into black and white parts because of github repo size limits.

Good luck and have fun!

GNU sed + bc, 4336 5074.5 points, 64 75 %

Update: the OP gave a new way to calculate the score of the prediction for an individual test case. Using Wolfram Alpha, I plotted both sets of formulas to see the differences.

The current way brings a strong incentive to output actual probabilities, and not just the extremes, 0 and 1, for which the new formulas give the same maximum score as before. This is why the unchanged algorithm below, has now a better prediction rate, in fact a great rate given its simplicity.

However, there's also a drawback associated with the new formulas, as explained in 'Edit 1'.

This is a simple estimation based only on the material advantage / disadvantage, ignoring the actual placement of the pieces. I was curious how this will perform. The reason I use sed, and not some language that can do this in one line, is because it is my favorite esoteric language.

/:/d                                             # delete the two headers
s:.*,::                                          # delete board positions
s:$:;Q9,R5,B3,N3,P1,K0,q-9,r-5,b-3,n-3,p-1,k-0:  # add relative piece value table
:r                                               # begin replacement loop
s:([a-Z])((.*)\1([^,]+)):\4+\2:                  # table lookup: letter-value repl.
tr                                               # repeat till last piece
s:;.*::                                          # delete value table
s:.*:echo '&0'|bc:e                              # get material difference: bc call
/^0$/c0.5                                        # print potential draw score
/-/c0                                            # print potential black win score
c1                                               # print potential white win score

Standard piece values used:

9 - Queen
5 - Rook
3 - Knight
3 - Bishop
1 - Pawn
0 - King

I calculate the material for both sides and subtract black's material from that of white. The output for each test case is based on that difference as follows:

if difference > 0, then output = 1 (potential white win)
if difference = 0, then output = 0.5 (potential draw).

This is my only fractional output, hence the reason of the improvement as explained above.

if difference < 0, then output = 0 (potential black win)

The prediction rate for this method was 64 %. Now it is 75 % with the new formulas.

   I initially expected it to be higher, say 70 %, but as a chess player myself I can understand the result, since I've lost so many games when I was +1 / +2, and won that many when I was down in material. It's all about the actual position. (Well, now I got my wish!)

Edit 1: the drawback

The trivial solution is to output 0.5 for each test case, because this way you scored half a point regardless who won. For our test cases, this meant a total score of 3392.5 points (50 %).

But with the new formulas, 0.5 (which is an output you'd give if you're undecided who wins) is converted to 0.75 points. Remember that the maximum score you can receive for a test case is 1, for 100% confidence in the winner. As such, the new total score for a constant 0.5 output is 5088.75 points, or 75 %! In my opinion, the incentive is too strong for this case.

That score is better, though marginally, than my material advantage based algorithm. The reason for that is because the algorithm gives a probability of 1 or 0 (no incentive), assumed wins or losses, more times (3831) than it gives 0.5 (incentive), assumed draws (2954). The method is simple in the end, and as such it doesn't have a high percentage of correct answers. The boost from the new formula to constant 0.5, manages to reach that percentage, artificially.

Edit 2:

It is a known fact, mentioned in chess books, that it is usually better to have a bishop pair than a knight pair. This is especially true in the middle to end stage of the game, where the test cases are, since it's more likely to have an open position where a bishop's range is increased.

Therefore I did a second test, but this time I replaced the bishops's value from 3 to 3.5. The knight's value remained 3. This is a personal preference, so I didn't make it my default submission. The total score in this case was 4411 points (65 %). Only 1 percentage point increase was observed.

With the new formulas, the total score is 4835 points (71 %). Now the weighted bishop underperforms. But, the effect is explained because the weighted method now gives even more times assumed wins or losses (5089), than assumed draws (1696).


Refactor variable names in JavaScript code Your challenge today is to refactor JavaScript code. You will take three strings as input; a JavaScript string, a old variable name, and the name you want to refactor it to. For example, an input of

"var x = 100; alert(x);", "x", "num"

Will output

"var num = 100; alert(num);"

Here's a more advanced test case:

"var gb = 1; var g = bg = 2; gb = bg = g = function(gg) { alert(gb); };
var str = 'g gb bg gg'; var regexp = /gb gb gb/g; //comment gb gb g g
/*gb gb g g*/", "gb", "aaa"

It should output

var aaa = 1; var g = bg = 2; aaa = bg = g = function(gg) { alert(aaa); };
var str = 'g gb bg gg'; var regexp = /gb gb g g/g; //comment gb gb g g
/*gb gb g g*/

And the same JS input with the other arguments "g", "aaa" should output

var gb = 1; var aaa = bg = 2; gb = bg = aaa = function(gg) { alert(gb); };
var str = 'g gb bg gg'; var regexp = /gb gb gb/g; //comment gb gb g g
/*gb gb g g*/

Here is one last much more complicated test case:

var g = 1; "g\"g"; "g'"; g; '"g\'g"g'; /g"\/*\//g; g; "// /*"; g; "*/"

It should output, with other parameters "g" and "a", this:

var a = 1; "g\"g"; "g'"; a; '"g\'g"g'; /g"\/*\//g; a; "// /*"; a; "*/"

(sidenote: I really like /g"\/*\//g; I think that's just evil :D)

Full specification:

For simplicity, you may ignore scope. Ex. "var a=1; function(){var a=2;}; var o={a: 3}", "a", "b" can output var b=1; function(){var b=2;}; var o={b: 3}.
Text in strings ('...' and "..."), regexps and their modifiers (/.../...), and comments (//...\n and /*...*/) must not be modified.
Also for simplicity, a valid identifier is one that starts with a letter, dollar sign, or underscore, and the rest of the characters are letters, numbers, dollar signs, or underscores.
You may assume that the input contains no syntax errors.
This is code-golf, so the shortest code in bytes will win.
If you use network access, all bytes downloaded from the network count towards your score.
You must use an actual programming language. No IDE solutions, like emacs or vim keystrokes. ;)

Ruby, 134 (113?) characters
*c,o,n=*$<;puts (c*?\n).gsub(/('|")((\\?+.)*?)\1|\/\*[\s\S]*?\*\/|\/\/.*|\/(\[\g<2>\]|\g<2>)+?\/\w*|([\w$]+)/){$5==o.chop&&n.chop||$&}

Unicode is not supported. If Unicode identifiers are to be supported, replace \w with [[:word:]]  and [\w$] with ([[:word:]]|\$) (and adjust the backreferences).
If unescaped slashes inside regexp literals (such as /[/]/) don't need to be supported, we can handle them together with string literals (116 characters). This also gives us string flags:
*c,o,n=*$<;puts (c*?\n).gsub(/\/\*[\s\S]*?\*\/|\/\/.*|('|"|\/)((\\?+.)*?)\1\w*|([\w$]+)/){$4==o.chop&&n.chop||$&}

Ungolfed version:
*code, old, new = *$<

puts code.join("\n").gsub (/
     ('|")((\\?+.)*?)\1           #strings
   | \/\*[\s\S]*?\*\/             #multiline comments
   | \/\/.*                       #single-line comments
   | \/(\[\g<2>\]|\g<2>)+?\/\w*   #regexes
   | ([\w$]+)                     #identifiers and keywords
/x){
  if $5 == old.chop then new.chop else $& end
}


Matrix Jigsaw Puzzle Pieces (Randomly inspired by https://codegolf.meta.stackexchange.com/a/17272/42963)

Given a rectangular matrix of digits (i.e., 0 - 9), output the "pieces" of the matrix as if the digits are connected together forming a single piece, in ascending order by the digits. The pieces are guaranteed to connect only orthongonally -- no piece will connect diagonally. There will only ever be a maximum of 10 pieces (i.e., a 3 piece won't appear twice in the same matrix).

For example, given the matrix

0 1 1 1
0 0 1 2
3 3 2 2

the following are the pieces, and an example output:

0
0 0

1 1 1
  1

  2
2 2

3 3

Spacing is important to keep the shape of the pieces, but the pieces do not necessarily need interior spacing. The pieces themselves should somehow be made distinct in a consistent manner (e.g., a newline between pieces, making sure each is a different character, etc.). Additionally, extraneous whitespace (for example, trailing newlines or leading columns) are not allowed. For example, the following would also be valid:

0
00
111
 1
 2
22
33

or

#
##

###
 #

 #
##

##

But the following would not be (note the trailing spaces behind the 0s):

0
0 0

Rotations or reflections are also not allowed. For example, outputting

 1
111

for the above matrix is also invalid.

The matrix pieces may have holes, or be only a single element:

0 0 0 1
0 2 0 1
0 0 0 3

Or, the piece may be the whole matrix:

0 0 0
0 0 0

Here's a larger, more complicated test case:

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

And an example output:

00

11111

 22
222
2

3

444
 44

55
5
5

6666
6  66
666

 77
  7
777

88

9

Rules and I/O

Input and output can be given by any convenient method.
You can print it to STDOUT or return it as a function result.
Either a full program or a function are acceptable.
Leading whitespace to keep the shape (e.g., the "T" shape of the 1 in the example) is required, consistent whitespace to make the pieces distinct, and a single trailing newline at the end is allowed, but no other whitespace is permitted.
You can safely assume that the pieces are numbered 0 to N contiguously, meaning that (for example) 3 wouldn't be skipped in a six-piece matrix.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Jelly, 18 bytes

ẎQṢ=€ẸƇZ$⁺œr€ɗ€0o⁶

Try it online!

Returns a list of pieces, where 1 represents a part of a piece, and ' ' is padding. Trailing ' 's are removed.


Write the shortest self-identifying program (a quine variant) Write a program that will generate a "true" output iff the input matches the source code of the program, and which generates a "false" output iff the input does not match the source code of the program.

This problem can be described as being related to quines, as the program must be able to somehow compute its own source code in the process.

This is code golf: standard rules apply.  Your program must not access any special files, such as the file of its own source code.

Edit: If you so choose, true/false can be replaced with True/False or 1/0.

Example

If the source code of your program is bhiofvewoibh46948732));:/)4, then here is what your program must do:

Input (Stdin)

bhiofvewoibh46948732));:/)4

Output (Stdout)

true

Input

(Anything other than your source code)

Output

false

JavaScript : 26

function f(s){return s==f}

I don't know if a JavaScript file really qualifies as a "program".


Self Scoring Program We have a challenge to output your own score, but it seems like all the answers there just hardcode the output and that's boring1.  So lets have a new challenge.  Your program must output its own length in bytes followed by the string " bytes", but in order to prevent hardcoded solutions if we reduce its size by removing any one byte, the new program must also output it's new byte count, still followed by " bytes".  Output does not need to be case sensitive. You may also choose to output a trailing newline.

Your answers will be scored in bytes with fewer bytes being better.

1: I actually like some of the answers there.

Backhand, 40 36 29 bytes

vv""sseettyybb  ""jjHHOO]

Try it online! Verification!

When in doubt, double up on everything. This uses Backhand's ability to move more than one step at a time to implement the redundancy. The unprintables all have the byte value 28.

Explanation:

Non-irradiated program:

v       Reduce step count to 2
  "    Start string literal
    s e t y b        Push the " bytes" part of the output
                  " Push 28 twice and end the string literal
                       j    Jump to the 28th position (0 indexed)
                             ]   Increment the 28 to 29
                           O     Print the 29
                         H       Halt and output the entire stack

Irradiated program:

If any character is deleted, every character after that is shifted down.

vv"sseettyybb
v " s e t y b     The same instructions are still executed

However, instead of jumping to the ], it instead reflects off the end of the program and lands on the O instead.

                             v  28th character (0 indexed)
vv""sseettyybb       ""jjHHOO]
v""sseettyybb       ""jjHHOO]OOHHjj"".....
                             ^ 28th character, reflecting off the end of the code


Program an Uncircularness Score Your task is to program a mathematical function s, that takes a nonempty finite set A of points in the 2D plane, and outputs an uncircularity score s(A) that satisfies following properties:

Positive Definiteness: If there is a circle or a straight line that contains all points of A, then s(A) = 0. Otherwise s(A) > 0

Surjectivity: It is surjective to the nonnegative real numbers, that means for every nonnegative real number r there is a finite subset A of the plane such that s(A) = r.

Translation Invariance: s is translation invariant if s(A) = s(A + v) for every vector v and for all A.

Scale Invariance: s is scale invariant, if s(A) = s(A * t) for every t≠0 and for all A.

Continuity. s is said to be continuous if the function f(p) := s(A ∪ {p}) (mapping the a point p to a real number) is continuous using the standard absolute value on the real numbers, and the standard euclidean norm on the points of the plane.

Intuitively speaking this uncircularness score can be thought of as something similar to the correlation coefficient in linear regression.
Details
Your function in theory has to work in the reals, but for the purpose of this challenge you can use floating point numbers as substitute. Please provide an explanation of your submission and an argument why those five properties hold. You can take two lists of coordinates or a list of tuples or similar formats as input. You can assume that no point in the input is repeated i.e. all points are unique.

Python 2 with numpy, 116 bytes

from numpy import*
def f(x,y):a=linalg.lstsq(hstack((x,y,ones_like(x))),(x*x+y*y)/2);return a[1]/sum((x-a[0][0])**4)

Takes x and y as 2d column vectors and returns an array containing the answer.  Note that this will give an empty array for a perfectly straight line or with 3 or fewer points.  I think lstsq gives no residuals if there's a perfect fit.

Explanation

Essentially, this finds the circle of best fit and gets the squared residuals.

We want to minimize (x - x_center)^2 + (y - y_center)^2 - R^2.  It looks nasty and nonlinear, but we can rewrite that as x_center(-2x) + y_center(-2y) + stuff = x^2 + y^2, where the stuff is still nasty and nonlinear in terms of x_center, y_center, and R, but we don't need to care about it.  So we can just solve [-2x -2y 1][x_center, y_center, stuff]^T = [x^2 + y^2].

We could then back out R if we really wanted, but that doesn't help us much here.  Thankfully, the lstsq function can give us the residuals, which satisfies most of the conditions.  Subtracting the center and scaling by (R^2)^2 = R^4 ~ x^4 gives us translational and scale invariance.

This is positive definite because the squared residuals are nonnegative, and we're dividing by a square.  It tends toward 0 for circles and lines because we're fitting a circle.
I'm fairly sure it's not surjective, but I can't get a good bound. If there is an upper bound, we can map [0, bound) to the nonnegative reals (for example, with 1 / (bound - answer) - 1 / bound) for a few more bytes.
We subtract out the center, so it's translationally invariant.
We divide by x**4, which removes the scale dependence.
It's composed of continuous functions, so it's continuous.


Print n weird numbers A weird number is a number that the sum of proper divisors is greater than the number itself and no subset of proper divisors sum to that number.
Examples:

70 is a weird number because its proper divisors (1, 2, 5, 7, 10, 14, and 35) sum to 74, which is greater than 70, and no combination of these numbers sum to 70.
18 is not a weird number because its proper divisors (1, 2, 3, 4, 6, 9) sum to 25, which is greater than 18, but 3, 6, and 9 sum to 18.

Your task is to write the shortest program that inputs through std-in any number n and calculates and prints to a file or std-out the first n weird numbers with newline separation.  No hard coding of the answers is allowed (sorry for not specifying this in the beginning).
For more examples, see this page: http://mathworld.wolfram.com/WeirdNumber.html

Haskell - 129

I'm sure there's lots to golf here, but since the competition seems low for now I'll throw this in.

Don't try running this though, I managed to wait only the two first elements, third will start taking minutes.

(%)=filter
w n=take n$e%[1..]
e x=let d=((==0).mod x)%[1..x-1]in sum d>x&&all((/=x).sum)(i d)
i[]=[[]]
i(y:z)=map(y:)(i z)++(i z)


Find the maximum deviation This problem is "inspired" from a question that was originally asked on Quora (not for code golfing). I just want to make it a challenge for you guys (and my first problem submission here).

Given an array of integer elements v and an integer d (we assume that d is lower or equal to the array's length), consider all the sequences of d consecutive elements in the array. For each sequence, compute the difference between the maximum and minimum value of the elements in that sequence and name it the deviation.

Your task is to write a program or function that computes the maximum value among all deviations of all the sequences considered above, and return or output that value.

Worked-through Example:

v: (6,9,4,7,4,1)
d: 3

The sequences of length 3 are:
6,9,4 with deviation 5
9,4,7 with deviation 5
4,7,4 with deviation 3
7,4,1 with deviation 6

Thus the maximal deviation is 6, so the output is 6.

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

Dyalog APL, 7 bytes

⌈/⌈/-⌊/

Test it on TryAPL.

How it works

⌈/⌈/-⌊/  Dyadic chain. Left argument: d. Right argument: v

     ⌊/  Reduce v by d-wise minimum, yielding the minima of all slices of length d.
  ⌈/     Reduce v by d-wise maximum, yielding the maxima of all slices of length d.
    -    Subtract, yielding the ranges of all slices of length d.
⌈/       Take the maximum.


Digital Cellular Automata Write a program or function that takes in an odd positive integer N and a string of decimal digits (0123456789). The string represents a ten-state one-dimensional cellular automaton. Each digit occupies one cell and the update rule from one generation to the next is that every cell becomes the digit resulting from the sum of the N cells centered on the cell, modulo 10.
The first and last cells wrap around as if neighbors, so cells can always have N cells centered on them. Note that N may be larger than the length of the string, which means it could wrap around multiple times and some digits will accordingly be in the sum multiple times.
As an example, if N is 7 and the string is 038, to visualize the cells to sum we can write 038 repeating infinitely in both directions
...038038038038038...

then the digit that the 0 will change into is the sum of the 7 digits centered around any 0, modulo 10:
...038038038038038...
      ^_____^
         |
    sum all these

This is (0+3+8+0+3+8+0)%10, which is 2.
Similarly the digits the 3 and 8 change into are defined by (3+8+0+3+8+0+3)%10 = 5 and (8+0+3+8+0+3+8)%10 = 0 respectively.
Thus, the generation after 038 is 250 when N is 7.
Your program or function needs to print or return the digit string of the very next generation of the input digit string. i.e. apply the update rule once to each cell and give the output. The shortest code in bytes wins.
Test Cases
[digit string] -> [N = 1], [N = 3], [N = 5], [N = 7], [N = 9], [N = 43]
0 -> 0, 0, 0, 0, 0, 0
1 -> 1, 3, 5, 7, 9, 3
2 -> 2, 6, 0, 4, 8, 6
3 -> 3, 9, 5, 1, 7, 9
4 -> 4, 2, 0, 8, 6, 2
5 -> 5, 5, 5, 5, 5, 5
6 -> 6, 8, 0, 2, 4, 8
7 -> 7, 1, 5, 9, 3, 1
8 -> 8, 4, 0, 6, 2, 4
9 -> 9, 7, 5, 3, 1, 7
00 -> 00, 00, 00, 00, 00, 00
07 -> 07, 47, 41, 81, 85, 47
10 -> 10, 12, 32, 34, 54, 12
11 -> 11, 33, 55, 77, 99, 33
12 -> 12, 54, 78, 10, 34, 54
34 -> 34, 10, 78, 54, 12, 10
66 -> 66, 88, 00, 22, 44, 88
80 -> 80, 86, 46, 42, 02, 86
038 -> 038, 111, 294, 250, 333, 472
101 -> 101, 222, 343, 545, 666, 989
987 -> 987, 444, 901, 765, 222, 543
1234 -> 1234, 7698, 3412, 9876, 1234, 7698
26697 -> 26697, 54128, 00000, 56982, 84413, 54128
001002 -> 001002, 211122, 331332, 335334, 455544, 113112
129577020 -> 129577020, 326194923, 474081605, 961120291, 333333333, 183342413
6023845292173530 -> 6023845292173530, 6853571632015189, 1197228291289874, 9238433109901549, 0110956118726779, 1982123699138828

CJam, 21 bytes

l~_,\2/f-l:~fm>:.+Af%

Test it here.

Explanation

l~   e# Read and evaluate N.
_,   e# Duplicate and turn into range [0 1 ... N-1]
\2/  e# Swap with other copy and (integer) divide by 2.
f-   e# Subtract this from each element in the range to get
     e# [-(N-1)/2 ... -1 0 1 ... (N-1)/2]
l:~  e# Read string and evaluate each digit separately.
fm>  e# Make one copy of the result for each element i in the range, shifting the array
     e# i cells to the right, cyclically.
:.+  e# Sum the columns of the resulting matrix.
Af%  e# Take each of those sums modulo 10.