Title: A Numpad's Knight Numbers

Body:
grep 58 bytes

grep "^((?=18|16|29|27|34|38|49|43|61|67|72|76|81|83|94|92).)*.$"

Because really, if you cannot beat grep...


问:
A Numpad's Knight Numbers
For the non-zero digits on a standard numpad

```<code>789
456
123
</code>```

consider placing a chess knight at any digit and moving it around with any number of normal L-shaped jumps, tracing out a positive decimal integer. What positive integers can be expressed in such a way?

One of them is 38, since the knight could start on the 3 and move left and up to the 8. 381 and 383 are also possible.

3 itself is possible if no jumps are taken (which is allowed). 5 is as well, but no other digits can be reached from the 5, so it is the only number where the digit 5 appears.

Write a program or function that takes in a positive decimal integer (you may take it as a string if desired) and prints or returns a truthy value if the number can be expressed by a knight on a numpad in the way described, but otherwise outputs a falsy value.

The shortest code in bytes wins. Tiebreaker is earlier answer

Examples

Truthy:

```<code>1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 18, 38, 61, 81, 294, 349, 381, 383, 729, 767, 38183, 38383, 18349276, 183492761, 618349276
</code>```

Falsy:

```<code>10, 11, 50, 53, 55, 65, 95, 100, 180, 182, 184, 185, 186, 187, 188, 189, 209, 305, 2009, 5030, 3838384, 4838383, 183492760
</code>```

答:
PowerShell v2+, <s>105</s> 96 bytes

```<code>param($a)((1..$a.length|%{'27618349294381672'.IndexOf($a[$_-1]+$a[$_])+1})-join'*'|iex)-or$a-eq5
</code>```

Iterates through the input (which must be encapsulated with "") by verifying that the index of any sequential pair of characters is in the valid lookup string. I see Kevin Lau had something similar, but I came up with this independently. Each of those indices are added with +1, as the .IndexOf() function will return -1 if the string isn't found. This will turn "not found"s into 0.

We then -join all the resultant integer values with * and pipe that to iex (similar to eval). This will mean if any one of the indices is not found, the entire expression will result in 0. That is encapsulated in parens and -or'd with $a-eq5 for the special case of input "5" to achieve our resultant output.

Test Runs

```<code>PS C:\Tools\Scripts\golfing> 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 18, 38, 61, 81, 294, 349, 381, 383, 729, 767, 38183, 38383, 18349276, 183492761, 618349276 | %{.\numpad-knight-numbers.ps1 "$_"}
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True

PS C:\Tools\Scripts\golfing> 10, 11, 50, 53, 55, 65, 95, 100, 180, 182, 184, 185, 186, 187, 188, 189, 209, 305, 2009, 5030, 3838384, 4838383, 183492760 | %{.\numpad-knight-numbers.ps1 "$_"}
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
</code>```

ContentLicense: CC BY-SA 3.0

Title: A Numpad's Knight Numbers

Body:
PowerShell v2+, <s>105</s> 96 bytes

param($a)((1..$a.length|%{'27618349294381672'.IndexOf($a[$_-1]+$a[$_])+1})-join'*'|iex)-or$a-eq5

Iterates through the input (which must be encapsulated with "") by verifying that the index of any sequential pair of characters is in the valid lookup string. I see Kevin Lau had something similar, but I came up with this independently. Each of those indices are added with +1, as the .IndexOf() function will return -1 if the string isn't found. This will turn "not found"s into 0.

We then -join all the resultant integer values with * and pipe that to iex (similar to eval). This will mean if any one of the indices is not found, the entire expression will result in 0. That is encapsulated in parens and -or'd with $a-eq5 for the special case of input "5" to achieve our resultant output.

Test Runs

PS C:\Tools\Scripts\golfing> 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 18, 38, 61, 81, 294, 349, 381, 383, 729, 767, 38183, 38383, 18349276, 183492761, 618349276 | %{.\numpad-knight-numbers.ps1 "$_"}
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True

PS C:\Tools\Scripts\golfing> 10, 11, 50, 53, 55, 65, 95, 100, 180, 182, 184, 185, 186, 187, 188, 189, 209, 305, 2009, 5030, 3838384, 4838383, 183492760 | %{.\numpad-knight-numbers.ps1 "$_"}
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False


答:
05AB1E, 29 bytes

Code:

```<code>"1Ôž±ÎqäÚ"•5(«U2÷¹¦2÷«vXyå})P
</code>```

Uses CP-1252 encoding. Try it online!.

Title: A Numpad's Knight Numbers

Body:
For the non-zero digits on a standard numpad

```<code>789
456
123
</code>```

consider placing a chess knight at any digit and moving it around with any number of normal L-shaped jumps, tracing out a positive decimal integer. What positive integers can be expressed in such a way?

One of them is 38, since the knight could start on the 3 and move left and up to the 8. 381 and 383 are also possible.

3 itself is possible if no jumps are taken (which is allowed). 5 is as well, but no other digits can be reached from the 5, so it is the only number where the digit 5 appears.

Write a program or function that takes in a positive decimal integer (you may take it as a string if desired) and prints or returns a truthy value if the number can be expressed by a knight on a numpad in the way described, but otherwise outputs a falsy value.

The shortest code in bytes wins. Tiebreaker is earlier answer

Examples

Truthy:

```<code>1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 18, 38, 61, 81, 294, 349, 381, 383, 729, 767, 38183, 38383, 18349276, 183492761, 618349276
</code>```

Falsy:

```<code>10, 11, 50, 53, 55, 65, 95, 100, 180, 182, 184, 185, 186, 187, 188, 189, 209, 305, 2009, 5030, 3838384, 4838383, 183492760
</code>```

Body:
05AB1E, 29 bytes

Code:

"1Ôž±ÎqäÚ"•5(«U2÷¹¦2÷«vXyå})P

Uses CP-1252 encoding. Try it online!.


答:
Jelly, <s>19</s> <s>15</s> 14 bytes

```<code>Doȷ’d3ạ2\P€=2P
</code>```

Try it online! or verify all test cases.

How it works

```<code>Doȷ’d3ạ2\P€=2P  Main link. Argument: n (integer)

D               Convert n to base 10 (digit array).
  ȷ             Yield 1000.
 o              Logical OR. This replaces each 0 with 1000.
   ’            Decrement each digit.
    d3          Divmod; replace each digit k with [k:3, k%3].
      ạ2\       Pairwise reduce by absolute difference.
                For each pair of adjacent digits [i, j], this computes
                [abs(i:3 - j:3), abs(i%3 - j%3)].
         P€     Compute the product of each result.
                n is a Numpad's Knight Number iff all products yield 2.
           =2   Compare each product with 2.
             P  Multiply the resulting Booleans.
</code>```

Title: A Numpad's Knight Numbers

Body:
Jelly, <s>19</s> <s>15</s> 14 bytes

Doȷ’d3ạ2\P€=2P

Try it online! or verify all test cases.

How it works

Doȷ’d3ạ2\P€=2P  Main link. Argument: n (integer)

D               Convert n to base 10 (digit array).
  ȷ             Yield 1000.
 o              Logical OR. This replaces each 0 with 1000.
   ’            Decrement each digit.
    d3          Divmod; replace each digit k with [k:3, k%3].
      ạ2\       Pairwise reduce by absolute difference.
                For each pair of adjacent digits [i, j], this computes
                [abs(i:3 - j:3), abs(i%3 - j%3)].
         P€     Compute the product of each result.
                n is a Numpad's Knight Number iff all products yield 2.
           =2   Compare each product with 2.
             P  Multiply the resulting Booleans.


问:
Sort an Integer List

The Challenge

It's quite simple really, sort a list of numbers.

Details

You must sort a list of numbers in ascending order, without using any built-in sorting functions/libraries/etc (i.e. list.sort() in Python).

Input/output can be done in any method you choose, as long as it is human readable.

Standard loopholes are disallowed as always.

Shortest code in bytes wins.

You must explain/list what sort method you used (Bubble, Insertion, Selection, etc.)

Input will not contain duplicates.

Sample Input/Output

Input: 99,-2,53,4,67,55,23,43,88,-22,36,45

Output: -22,-2,4,23,36,43,45,53,55,67,88,99

Note: A near direct opposite of Sort a List of Numbers

答:
Awk, 66 bytes

```<code>{b=$0;a[b]}m<b{m=b}n>b{n=b}END{for(i=n;i<=m;i++)if(i in a)print i}
</code>```

Arrays in awk are like dictionaries, not like C arrays. The indexes can be non-contiguous, and they grow (and are created) as needed. So, we create an array a for the input, with each line being a key. And we save the min and max values. Then we loop from min to max, and print all keys which exist in a. b is just to avoid repeated usage of $0.

Title: Sort an Integer List

Body:
Awk, 66 bytes

{b=$0;a[b]}m<b{m=b}n>b{n=b}END{for(i=n;i<=m;i++)if(i in a)print i}

Arrays in awk are like dictionaries, not like C arrays. The indexes can be non-contiguous, and they grow (and are created) as needed. So, we create an array a for the input, with each line being a key. And we save the min and max values. Then we loop from min to max, and print all keys which exist in a. b is just to avoid repeated usage of $0.


问:
Convert to Roman Numeral!
Your task is to convert a given positive integer from Arabic numeral to Roman numeral.

Things get difficult when you count to 4000.

The romans did this by adding a line above a symbol to multiply that symbol by 1 000. However, overlines aren't exactly displayable in ASCII. Also, there are double overlines to multiply a symbol by 1 000 000, and then triple overline to multiply a symbol by 1 000 000 000, etc...

Therefore, I decided to use parentheses to replace overlines.

The symbols can be individually placed in parentheses. For example, both (VI) and (V)(I) are valid representations of 6 000. (V)M is also a valid representation of 6000.

(I) is a valid way to represent 1 000.

Testcases

```<code>Input: 1
Output: I
Input: 2
Output: II
Input: 3
Output: III
Input: 4
Output: IV
Input: 15
Output: XV
Input: 40
Output: XL
Input: 60
Output: LX
Input: 67
Output: LXVII
Input: 400
Output: CD
Input: 666
Output: DCLXVI
Input: 3000
Output: MMM
Input: 3999
Output: MMMCMXCIX
Input: 4000
Output: M(V)
Input: 4999
Output: M(V)CMXCIX
Input: 6000
Output: (VI)
Input: 6000000
Output: ((VI))
Input: 6006000
Output: ((VI)VI)
Input: 6666666666
Output: (((VI)DCLXVI)DCLXVI)DCLXVI
</code>```

Scoring

This is code-golf. Shortest code in bytes win.

答:
Common Lisp, 108

(defun p(n)(if(> n 0)(if(< n 4000)(format()"~@R"n)(format()"(~A)~@[~A~]"(p(floor n 1000))(p(mod n 1000))))))
```

<h2>Ungolfed</h2>

<pre class="lang-lisp prettyprint-override"><code>(defun p(n)
  (if (> n 0)
      (if (< n 4000)

          ;; Built-in Roman formatter (between 1 and 3999)
          (format () "~@R" n)

          ;; Divide N by 1000, as 1000*Q + R.
          ;; First print (p Q) in parentheses (recursively)
          ;; Then, if it is not NIL, the remainder R.
          (format () "(~A)~@[~A~]"
                  (p (floor n 1000))
                  (p (mod n 1000))))))
</code>```

Tests

Two tests give different outputs than the ones from the question:

(loop for (in out) in '((1 "I")
                        (2 "II")
                        (3 "III")
                        (4 "IV")
                        (15 "XV")
                        (40 "XL")
                        (60 "LX")
                        (67 "LXVII")
                        (400 "CD")
                        (666 "DCLXVI")
                        (3000 "MMM")
                        (3999 "MMMCMXCIX")
                        (4000 "M(V)")
                        (4999 "M(V)CMXCIX")
                        (6000 "(VI)")
                        (6000000 "((VI))")
                        (6006000 "((VI)VI)")
                        (6666666666 "(((VI)DCLXVI)DCLXVI)DCLXVI"))
   for computed = (p in)
   unless (string= out computed)
   collect (list in out computed))

=> ((4000 "M(V)" "(IV)")
    (4999 "M(V)CMXCIX" "(IV)CMXCIX"))
```

Title: Convert to Roman Numeral!

Body:
Common Lisp, 108

(defun p(n)(if(> n 0)(if(< n 4000)(format()"~@R"n)(format()"(~A)~@[~A~]"(p(floor n 1000))(p(mod n 1000))))))

Ungolfed

(defun p(n)
  (if (> n 0)
      (if (< n 4000)

          ;; Built-in Roman formatter (between 1 and 3999)
          (format () "~@R" n)

          ;; Divide N by 1000, as 1000*Q + R.
          ;; First print (p Q) in parentheses (recursively)
          ;; Then, if it is not NIL, the remainder R.
          (format () "(~A)~@[~A~]"
                  (p (floor n 1000))
                  (p (mod n 1000))))))

Tests

Two tests give different outputs than the ones from the question:

(loop for (in out) in '((1 "I")
                        (2 "II")
                        (3 "III")
                        (4 "IV")
                        (15 "XV")
                        (40 "XL")
                        (60 "LX")
                        (67 "LXVII")
                        (400 "CD")
                        (666 "DCLXVI")
                        (3000 "MMM")
                        (3999 "MMMCMXCIX")
                        (4000 "M(V)")
                        (4999 "M(V)CMXCIX")
                        (6000 "(VI)")
                        (6000000 "((VI))")
                        (6006000 "((VI)VI)")
                        (6666666666 "(((VI)DCLXVI)DCLXVI)DCLXVI"))
   for computed = (p in)
   unless (string= out computed)
   collect (list in out computed))

=> ((4000 "M(V)" "(IV)")
    (4999 "M(V)CMXCIX" "(IV)CMXCIX"))


答:
JavaScript (ES6), <s>65</s> 62 bytes

```<code>s=>[...s].every((c,i)=>!i|"16729438183492761".match(s[i-1]+c))
</code>```

Returns true or false. I'd previously tried a recursive solution, which takes 63 bytes, and map and even reduce but they took me 73 bytes.

Edit: Saved 3 bytes thanks to @user81655.

Title: A Numpad's Knight Numbers

Body:
JavaScript (ES6), <s>65</s> 62 bytes

s=>[...s].every((c,i)=>!i|"16729438183492761".match(s[i-1]+c))

Returns true or false. I'd previously tried a recursive solution, which takes 63 bytes, and map and even reduce but they took me 73 bytes.

Edit: Saved 3 bytes thanks to @user81655.


答:
Haskell 46 bytes

```<code>q=zip<*>tail
all(`elem`q"16729438183492761").q
</code>```

Usage example: all(`elem`q"16729438183492761").q $ "183492761" -> True

How it works: It uses the lookup string found in @Kevin Lau's answer. q makes a list of pairs of adjacent chars from a string, e.g. q "1672" -> [('1','6'),('6','7'),('7','2')]. The function returns true if all pairs from the input appear in the pairs from the lookup string. q turns single digit inputs into the empty list, so elem always succeeds.

Title: A Numpad's Knight Numbers

Body:
Haskell 46 bytes

q=zip<*>tail
all(`elem`q"16729438183492761").q

Usage example: all(`elem`q"16729438183492761").q $ "183492761" -> True

How it works: It uses the lookup string found in @Kevin Lau's answer. q makes a list of pairs of adjacent chars from a string, e.g. q "1672" -> [('1','6'),('6','7'),('7','2')]. The function returns true if all pairs from the input appear in the pairs from the lookup string. q turns single digit inputs into the empty list, so elem always succeeds.


答:
Python 2, 52 bytes

f=lambda n:n<6or`n%100`in'18349276167294381'*f(n/10)
```

Checks that any two consecutive digits are in the string '18349276167294381'. To get consecutive digits, rather than doing zip(`n`,`n`[1:]), the function repeatedly checks the last two digits and removes the last digit.

Title: A Numpad's Knight Numbers

Body:
Python 2, 52 bytes

f=lambda n:n<6or`n%100`in'18349276167294381'*f(n/10)

Checks that any two consecutive digits are in the string '18349276167294381'. To get consecutive digits, rather than doing zip(`n`,`n`[1:]), the function repeatedly checks the last two digits and removes the last digit.


答:
Ruby, <s>185 161</s> 144 bytes

```<code>r=->i{i>(t=1e3)? "(#{r[i/t]})"+r[i%t]:(s=?I*i;"IVXXLCCDM".scan(/(.)(.)(.)/){|x,y,z|{x*5=>y,x*4=>x+y,y*2=>z,y+x+y=>x+z}.map{|x,y|s.gsub!x,y}};s)}
</code>```

Over a year after the original post, I think I learned something about golfing.

Thank you Value Ink for your valuable comments.

Title: Convert to Roman Numeral!

Body:
Your task is to convert a given positive integer from Arabic numeral to Roman numeral.

Things get difficult when you count to 4000.

The romans did this by adding a line above a symbol to multiply that symbol by 1 000. However, overlines aren't exactly displayable in ASCII. Also, there are double overlines to multiply a symbol by 1 000 000, and then triple overline to multiply a symbol by 1 000 000 000, etc...

Therefore, I decided to use parentheses to replace overlines.

The symbols can be individually placed in parentheses. For example, both (VI) and (V)(I) are valid representations of 6 000. (V)M is also a valid representation of 6000.

(I) is a valid way to represent 1 000.

Testcases

```<code>Input: 1
Output: I
Input: 2
Output: II
Input: 3
Output: III
Input: 4
Output: IV
Input: 15
Output: XV
Input: 40
Output: XL
Input: 60
Output: LX
Input: 67
Output: LXVII
Input: 400
Output: CD
Input: 666
Output: DCLXVI
Input: 3000
Output: MMM
Input: 3999
Output: MMMCMXCIX
Input: 4000
Output: M(V)
Input: 4999
Output: M(V)CMXCIX
Input: 6000
Output: (VI)
Input: 6000000
Output: ((VI))
Input: 6006000
Output: ((VI)VI)
Input: 6666666666
Output: (((VI)DCLXVI)DCLXVI)DCLXVI
</code>```

Scoring

This is code-golf. Shortest code in bytes win.

Body:
Ruby, <s>185 161</s> 144 bytes

r=->i{i>(t=1e3)? "(#{r[i/t]})"+r[i%t]:(s=?I*i;"IVXXLCCDM".scan(/(.)(.)(.)/){|x,y,z|{x*5=>y,x*4=>x+y,y*2=>z,y+x+y=>x+z}.map{|x,y|s.gsub!x,y}};s)}

Over a year after the original post, I think I learned something about golfing.

Thank you Value Ink for your valuable comments.


问:
Are there More Hard Objects or Soft Objects
Tangentially inspired by the opening to the What-If book.

The input is a rectangle of spaces as a string, list of string, etc., with objects made of #'s inside:

```<code>########
#      #
########

   ###        ####
   ###        ####
   ###
</code>```

The objects will always be non-intersecting, non-touching, rectangles. A soft object is defined as an object that isn't filled up with #'s in the middle and is only a border, a hard object is one that is filled up. An object with width or height <=2 is considered hard. All objects are either hard or soft.

If there are more hard objects in the input, output "Hard", if more soft, output "Soft", if they are equal, output "Equal".

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

Test Cases

These cases aren't full inputs, but rather what each object should be characterized as. The actual input will be like the ascii-art at the top of the question.

Hard

```<code>#

####

##
##

##########
##########
##########
</code>```

Soft

```<code>###
# #
###

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

####
#  #
#  #
#  #
#  #
#  #
#  #
#  #
####
</code>```

Actual Test Cases

```<code>########
#      #
########

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

Hard

###
###
###

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

Equal

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

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

Soft
</code>```

答:
MATL, <s>105</s> <s>104</s> <s>58</s> <s>50</s> 49 bytes

Thanks to @Neil for a suggestion that allowed me to remove 46 bytes!

```<code>2\TTYaEq4:HeqgEqZ+K/Zot0>+ss'Soft Hard Equal'Ybw)
</code>```

Input is a 2D char array, with rows separated by ;. The example in the challenge is

```<code>['########          ';'#      #          ';'########          ';'                  ';'   ###        ####';'   ###        ####';'   ###            ']
</code>```

Here's another example:

```<code>['###                ';'###                ';'###                ';'                   ';'###################';'#                 #';'#                 #';'#                 #';'###################']
</code>```

This corresponds to

```<code>###
###
###

###################
#                 #
#                 #
#                 #
###################
</code>```

and thus should give 'Equal'.

As a third example, corresponding to 'Soft',

```<code>['   ######    ';'   #    #    ';'   ######    ';'          ###';'   ##  #  # #';'          ###';'             ';'             ';' ########    ';' #      #    ';' ########    ']
</code>```

that is,

```<code>   ######
   #    #
   ######
          ###
   ##  #  # #
          ###

 ########
 #      #
 ########
</code>```

Try it online!

Explanation

This uses 2D convolution to detect shapes. The input is converted to a 2D array with 1 indicating # and -1 for space; and is padded with a frame of -1 values. This assures that shapes at the edge of the original field are also detected.

A soft object is detected by the mask

```<code> 1   1
 1  -1
</code>```

which corresponds to the object's upper-left corner with one empty interior point. Note that the convolution inverts the mask, so it is defined as [-1 1; 1 1] in the code. The number S of positions in which the convolution equals 4 is the total number of soft objects.

An object (soft or hard) is detected by the mask

```<code>-1  -1
-1   1
</code>```

which correponds to the object's upper-left corner together with some empty exterior points. This mask is the negated version of the previous one, so the previous convolution result can be reused. Specifically, the number T of positions in which that result equals -4 is the total number of objects.

The number H of hard objects is T−S. The output string is determined by the sign of S−H = 2*S−T.

```<code>2\                 % Input. Modulo 2: '#' gives 1, ' ' gives 0
TTYa               % Add a frame of zeros
Eq                 % Convert 0 to -1
4:HeqgEq           % Generate mask [-1 1; 1 1], for soft objects
Z+                 % 2D convolution, preserving size
K/Zo               % Divide by 4 and round towards 0. Gives 1 or -1 for 4 or -4
t0>                % Duplicate. 1 for positive entries (soft objects), 0 otherwise
+                  % Add. This corresponds to the factor 2 that multiplies number S
ss                 % Sum of 2D array. Gives 2*S-T
'Soft Hard Equal'  % Push this string
Yb                 % Split by spaces. Gives cell array
w)                 % Swap. Apply (modular) index to select one string
</code>```

Body:
MATL, <s>105</s> <s>104</s> <s>58</s> <s>50</s> 49 bytes

Thanks to @Neil for a suggestion that allowed me to remove 46 bytes!

2\TTYaEq4:HeqgEqZ+K/Zot0>+ss'Soft Hard Equal'Ybw)

Input is a 2D char array, with rows separated by ;. The example in the challenge is

['########          ';'#      #          ';'########          ';'                  ';'   ###        ####';'   ###        ####';'   ###            ']

Here's another example:

['###                ';'###                ';'###                ';'                   ';'###################';'#                 #';'#                 #';'#                 #';'###################']

This corresponds to

###
###
###

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

and thus should give 'Equal'.

As a third example, corresponding to 'Soft',

['   ######    ';'   #    #    ';'   ######    ';'          ###';'   ##  #  # #';'          ###';'             ';'             ';' ########    ';' #      #    ';' ########    ']

that is,

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

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

Try it online!

Explanation

This uses 2D convolution to detect shapes. The input is converted to a 2D array with 1 indicating # and -1 for space; and is padded with a frame of -1 values. This assures that shapes at the edge of the original field are also detected.

A soft object is detected by the mask

 1   1
 1  -1

which corresponds to the object's upper-left corner with one empty interior point. Note that the convolution inverts the mask, so it is defined as [-1 1; 1 1] in the code. The number S of positions in which the convolution equals 4 is the total number of soft objects.

An object (soft or hard) is detected by the mask

-1  -1
-1   1

which correponds to the object's upper-left corner together with some empty exterior points. This mask is the negated version of the previous one, so the previous convolution result can be reused. Specifically, the number T of positions in which that result equals -4 is the total number of objects.

The number H of hard objects is T−S. The output string is determined by the sign of S−H = 2*S−T.

2\                 % Input. Modulo 2: '#' gives 1, ' ' gives 0
TTYa               % Add a frame of zeros
Eq                 % Convert 0 to -1
4:HeqgEq           % Generate mask [-1 1; 1 1], for soft objects
Z+                 % 2D convolution, preserving size
K/Zo               % Divide by 4 and round towards 0. Gives 1 or -1 for 4 or -4
t0>                % Duplicate. 1 for positive entries (soft objects), 0 otherwise
+                  % Add. This corresponds to the factor 2 that multiplies number S
ss                 % Sum of 2D array. Gives 2*S-T
'Soft Hard Equal'  % Push this string
Yb                 % Split by spaces. Gives cell array
w)                 % Swap. Apply (modular) index to select one string


答:
MATL, <s>25</s> <s>24</s> <s>33</s> 26 bytes

Shaved off 1 byte thanks to @LuisMendo!

@Dennis found a bug, and then fixed it! Thanks!

```<code>'bSVYXbTUZW'j47-)d2^48\1=A
</code>```

Takes integer as input. Outputs 1/0.

Try it online!

Title: A Numpad's Knight Numbers

Body:
MATL, <s>25</s> <s>24</s> <s>33</s> 26 bytes

Shaved off 1 byte thanks to @LuisMendo!

@Dennis found a bug, and then fixed it! Thanks!

'bSVYXbTUZW'j47-)d2^48\1=A

Takes integer as input. Outputs 1/0.

Try it online!


问:
Choose The Powerball Numbers!
Powerball is an American lottery that has recently gained attention because the current jackpot (as of January 11, 2016) is the largest lotto prize in history, at about $1.5 billion (USD).

Powerball players choose 5 distinct numbers from 69 numbered white balls, and 1 one "Powerball" number from 26 numbered red balls. They win the jackpot if their five white ball choices match what was drawn in any order, and if they chose the correct "Powerball" number.

So the chances of winning the jackpot are 1 in (69 choose 5)*(26 choose 1) or ((69*68*67*66*65)/(5*4*3*2*1))*26, which is 1 in 292,201,338

No one won the jackpot in the most recent drawing on January 9, 2016, but perhaps someone will win the next drawing on January 13, 2016, 10:59 pm ET.

Challenge

Write a program or function that simulates a Powerball drawing, taking no input but outputting 5 distinct random numbers from 1 to 69 inclusive, and then one random "Powerball" number from 1 to 26 inclusive (which could be a repeat of one of the 5 initial numbers).

The "Powerball" number should always be the last number in the output, but otherwise the order of the first 5 numbers does not matter.

The 6 numbers should be output in decimal, either space separated or newline separated, with an optional single trailing newline. Commas, brackets, and other characters are not allowed in the output.

So these would be  valid outputs (using the numbers from the last drawing):

```<code>32 16 19 57 34 13</code>```
```<code>32
16
19
57
34
13</code>```

All 292201338 possible outcomes should be possible with uniform probability. You may use built-in pseudo-random number generators and assume they meet this standard.

Here is an ungolfed reference implementation that works in Python 2 or 3:

import random
print(' '.join(map(str, random.sample(range(1,70), 5) + [random.randint(1, 26)])))
```

The shortest code in bytes wins.

Note that I have no affiliation with Powerball and don't really suggest that you play. But if you win anything from numbers generated by one of the programs here, I'm sure we'd love to hear about it. :D

答:
PHP, 65 bytes

```<code><?=join(' ',array_rand(array_flip(range(1,69)),5))." ".rand()%26;
</code>```

Thanks to the other PHP answer on this page. I wrote up a program on my own, and it turned out to be the exact same answer as the one written by Samsquanch, which drove me to take it a step further to save a few bytes.

If anyone can figure out a way to append one array to another in here that's less than the 5 bytes it takes me to join the powerball number on after, I would greatly appreciate it, cause it's driving me nuts! The best I could come up with would be after array_rand and before join, having a statement something like +[5=>rand()%25], but that's an extra byte over just concatenating it on after.

```<code><?=                                                              // This represents an inline 'echo' statement
                                  range(1,69)                    // Get an array of all numbers from 1 to 69 inclusive
                       array_flip(           )                   // Swap the keys and values.
            array_rand(                       ,5)                // Get a random subset of five keys.
   join(' ',                                     ).rand()%26     // Concatenate the array with spaces, along with the powerball number
</code>```

Run it through the command line. Sample:

```<code>C:\(filepath)>php powerball.php
</code>```

Output:

```<code> 12 24 33 67 69 4
</code>```

Title: Choose The Powerball Numbers!

Body:
PHP, 65 bytes

<?=join(' ',array_rand(array_flip(range(1,69)),5))." ".rand()%26;

Thanks to the other PHP answer on this page. I wrote up a program on my own, and it turned out to be the exact same answer as the one written by Samsquanch, which drove me to take it a step further to save a few bytes.

If anyone can figure out a way to append one array to another in here that's less than the 5 bytes it takes me to join the powerball number on after, I would greatly appreciate it, cause it's driving me nuts! The best I could come up with would be after array_rand and before join, having a statement something like +[5=>rand()%25], but that's an extra byte over just concatenating it on after.

<?=                                                              // This represents an inline 'echo' statement
                                  range(1,69)                    // Get an array of all numbers from 1 to 69 inclusive
                       array_flip(           )                   // Swap the keys and values.
            array_rand(                       ,5)                // Get a random subset of five keys.
   join(' ',                                     ).rand()%26     // Concatenate the array with spaces, along with the powerball number

Run it through the command line. Sample:

C:\(filepath)>php powerball.php

Output:

 12 24 33 67 69 4


问:
Substitution cipher
A substitution cipher is an encoding method where each letter in the alphabet is replaced with a fixed, different one; for example, given the following substitution map:

```<code>abcdefghijklmnopqrstuvwxyz
            ||
qwertyuiopasdfghjklzxcvbnm
</code>```

The phrase "we all love cryptography" would be encoded as "vt qss sgct eknhzgukqhin".

The program will continuously read its input, one line at time; the first line will contain the substitution map, in the form of all 26 letters, in any order, without repetitions, missing letters or extraneous characters; it will be interpreted as "the first letter is the substitution for A, the second letter is the substitution for B [...] the 26th letter is the substitution for Z"; no output will be provided after reading it.
For each subsequent line, the program will output the encoded text corresponding to the line. Only letters will be encoded; numbers, symbols and whitespaces will be simply copied to the output.

For simplicity, all input (including the substitution map) will only contain lowercase characters.

Sample input:

```<code>qwertyuiopasdfghjklzxcvbnm
hello
bye!
i don't know.
</code>```

Sample output:

```<code>itssg
wnt!
o rgf'z afgv.
</code>```

As usual, the shortest solution wins.

Additional clarifications on input:

The program must read its input stream (I thought that was clear); command line parameters, files, named pipes, network sockets, quantum entanglement or extra sensorial perceptions are not allowed.

The input must include only the actual text to be processed; quotes, brackets, commas or any other symbol, if found, should simply be copied to the output as they are.

No additional characters should be required in the input. If your program requires the input text to be placed in quotes, brackets, commas or any other delimiter, then You Are Doing It Wrong (TM).

"Line" is defined as a string of characters followed by a newline; the actual implementation of "newline" if usually left to the OS, but if you need to go into its details, just use whatever you prefer.

An empty line is no special case; the program could either print an empty line or do nothing, but it should not print any actual text, crash, exit, destroy the operating system, set fire to the house, collapse the Sun in a black hole, summon demons from other planes of existence or replace your toothpaste with mayonnaise.

There is no requirement for the program to run interactively; it's free to suck all its input in and then print all its output; there is also not any time limit on its execution, although it would be definitely preferable for it to terminate before the heat death of the universe.

答:
Factor, 155 bytes

The logic is actually pretty simple, it's just constraining to the REPL requirement that costs.

```<code>[let "abcdefghijklmnopqrstuvwxyz" readln string>array bi@ zip :> T [ t ] [ T readln string>array [ dup T key? [ T at ] [ ] if ] map "" join print ] while ]
</code>```

Readable single-function version (don't ever write code like this):

```<code>:: monolithic-repl ( -- )
    "abcdefghijklmnopqrstuvwxyz" readln string>array bi@ zip
  :> table
  [ t ]
  [ table readln string>array
    [ dup table key?
      [ table at ] [ ] if
    ] map
    "" join print
  ] while ;
</code>```

Readable, Factored version:

```<code>:: cipher-print ( cipher-table -- )
  readln string>array
  [ dup cipher-table key? [ cipher-table at ] [ ] if ] map
  "" join print ;

: cipher-get ( -- cipher )
  "abcdefghijklmnopqrstuvwxyz" readln
  string>array bi@ zip ;

:: cipher-repl ( -- )
  cipher-get :> table
  [ t ] [ table cipher-print ] while ;
</code>```

Title: Substitution cipher

Body:
Factor, 155 bytes

The logic is actually pretty simple, it's just constraining to the REPL requirement that costs.

[let "abcdefghijklmnopqrstuvwxyz" readln string>array bi@ zip :> T [ t ] [ T readln string>array [ dup T key? [ T at ] [ ] if ] map "" join print ] while ]

Readable single-function version (don't ever write code like this):

:: monolithic-repl ( -- )
    "abcdefghijklmnopqrstuvwxyz" readln string>array bi@ zip
  :> table
  [ t ]
  [ table readln string>array
    [ dup table key?
      [ table at ] [ ] if
    ] map
    "" join print
  ] while ;

Readable, Factored version:

:: cipher-print ( cipher-table -- )
  readln string>array
  [ dup cipher-table key? [ cipher-table at ] [ ] if ] map
  "" join print ;

: cipher-get ( -- cipher )
  "abcdefghijklmnopqrstuvwxyz" readln
  string>array bi@ zip ;

:: cipher-repl ( -- )
  cipher-get :> table
  [ t ] [ table cipher-print ] while ;


答:
JavaScript (ES6), <s>123</s> <s>121</s> 118 bytes

s=>s.replace(/#+/g,(m,i)=>s[i+l]>" "?0:n+=!m[1]|s[i-l+1]==s[i-l]||-1,n=l=~s.search`
|$`)|n>l?"Hard":n<l?"Soft":"Equal"
```

<p><em>Saved 2 bytes thanks to @edc65!</em></p>

<p>Takes input as a multiline string padded with spaces to form a grid.</p>

<h2>Explanation / Test</h2>

<p><s>Very close to MATL length!</s> Basically, it searches for the top line of <code>#</code>s of each object, and if the length of the top line is less than 2 or the first 2 characters below the top line are the same, it is hard, otherwise soft.</p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var solution =

s=>
  s.replace(/#+/g,(m,i)=>        // for each run of consecutive # characters
    s[i+l]>" "?                  // if the position above the match contains a #
      0                          // do nothing (this object has already been counted)
    :n+=                         // add 1 to the counter (hard) if
      !m[1]                      // the match is only 1 # wide
      |s[i-l+1]==s[i-l]          // or the characters below are the same
      ||-1,                      // else decrement the counter (soft)
    n=                           // n = counter, hard objects increase n, soft decrease
    l=~s.search`\n|$`            // l = (negative) line length
  )
  |n>l?"Hard":n<l?"Soft":"Equal" // return the result string

// Test
document.write("```" + [`

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

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

`,`

###
###
###

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

`,`

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

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

`,`

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

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

`,`

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

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

`,`

#

`,`

##

`,`

#
#

`,`

###
# #
###

`].map((test) => solution(test.slice(2, -2))).join("\n")
)```

Title: Are there More Hard Objects or Soft Objects

Body:
Tangentially inspired by the opening to the What-If book.

The input is a rectangle of spaces as a string, list of string, etc., with objects made of #'s inside:

```<code>########
#      #
########

   ###        ####
   ###        ####
   ###
</code>```

The objects will always be non-intersecting, non-touching, rectangles. A soft object is defined as an object that isn't filled up with #'s in the middle and is only a border, a hard object is one that is filled up. An object with width or height <=2 is considered hard. All objects are either hard or soft.

If there are more hard objects in the input, output "Hard", if more soft, output "Soft", if they are equal, output "Equal".

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

Test Cases

These cases aren't full inputs, but rather what each object should be characterized as. The actual input will be like the ascii-art at the top of the question.

Hard

```<code>#

####

##
##

##########
##########
##########
</code>```

Soft

```<code>###
# #
###

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

####
#  #
#  #
#  #
#  #
#  #
#  #
#  #
####
</code>```

Actual Test Cases

```<code>########
#      #
########

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

Hard

###
###
###

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

Equal

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

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

Soft
</code>```

Body:
JavaScript (ES6), <s>123</s> <s>121</s> 118 bytes

s=>s.replace(/#+/g,(m,i)=>s[i+l]>" "?0:n+=!m[1]|s[i-l+1]==s[i-l]||-1,n=l=~s.search`
|$`)|n>l?"Hard":n<l?"Soft":"Equal"

Saved 2 bytes thanks to @edc65!

Takes input as a multiline string padded with spaces to form a grid.

Explanation / Test

<s>Very close to MATL length!</s> Basically, it searches for the top line of #s of each object, and if the length of the top line is less than 2 or the first 2 characters below the top line are the same, it is hard, otherwise soft.

var solution =

s=>
  s.replace(/#+/g,(m,i)=>        // for each run of consecutive # characters
    s[i+l]>" "?                  // if the position above the match contains a #
      0                          // do nothing (this object has already been counted)
    :n+=                         // add 1 to the counter (hard) if
      !m[1]                      // the match is only 1 # wide
      |s[i-l+1]==s[i-l]          // or the characters below are the same
      ||-1,                      // else decrement the counter (soft)
    n=                           // n = counter, hard objects increase n, soft decrease
    l=~s.search`\n|$`            // l = (negative) line length
  )
  |n>l?"Hard":n<l?"Soft":"Equal" // return the result string

// Test
document.write("<pre>" + [`

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

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

`,`

###
###
###

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

`,`

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

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

`,`

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

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

`,`

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

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

`,`

#

`,`

##

`,`

#
#

`,`

###
# #
###

`].map((test) => solution(test.slice(2, -2))).join("\n")
)


Title: A Numpad's Knight Numbers

Body:
Julia, <s>51</s> 49 bytes

n->diff(["@1634@8725"...][digits(n)+1]).^2%48⊆1

Verification

julia> f=n->diff(["@1634@8725"...][digits(n)+1]).^2%48⊆1
(anonymous function)

julia> all(map(f,(1,2,3,4,5,6,7,8,9,16,18,38,61,81,294,349,381,383,729,767,38183,38383,18349276,183492761,618349276)))
true

julia> any(map(f,(10,11,50,53,55,65,95,100,180,182,184,185,186,187,188,189,209,305,2009,5030,3838384,4838383,183492760)))
false


问:
Form tiles in a rectangular ring
Given the input tilesX and tilesY create a method that would make a rectangular ring from the tiles.

The function must order the tiles in a ring like this:

tilesX and tilesY are always positive integer values, cannot be 0

tilesX and tilesY are not always equal, expect values like: 2x5, 6x3 etc.

Checking for invalid input is not necessary

You can use any way to display the tiles, including 2d arrays, ASCII art or printed text.

There's no strict way how the input is passed as long as it's two integers.

Cannot be a line, drawing a rectangle size of tilesX and tilesY pixels is not valid

The shortest code wins

答:
QBasic, 69 bytes

```<code>INPUT x,y
FOR i=1TO y
FOR j=1TO x
?i MOD y<2OR j MOD x<2;
NEXT
?
NEXT
</code>```

Takes dimensions as width,height. The boolean value from the is-it-on-the-border test is simply printed: -1 for true and 0 for false. A sample run looks like:

```<code>? 5,3
-1 -1 -1 -1 -1
-1  0  0  0 -1
-1 -1 -1 -1 -1
</code>```

Bonus: Graphical version, 88 bytes

```<code>INPUT x,y
SCREEN 9
FOR i=1TO y
FOR j=1TO x
PSET(j*3,i*3),i MOD y<2OR j MOD x<2
NEXT
NEXT
</code>```

I believe this counts as "not a line." When the MOD expression is false (0), PSET plots a black pixel; when it's true (-1), PSET apparently plots a white pixel. Here's 17,31, shown at 2x size:

Title: Form tiles in a rectangular ring

Body:
QBasic, 69 bytes

INPUT x,y
FOR i=1TO y
FOR j=1TO x
?i MOD y<2OR j MOD x<2;
NEXT
?
NEXT

Takes dimensions as width,height. The boolean value from the is-it-on-the-border test is simply printed: -1 for true and 0 for false. A sample run looks like:

? 5,3
-1 -1 -1 -1 -1
-1  0  0  0 -1
-1 -1 -1 -1 -1

Bonus: Graphical version, 88 bytes

INPUT x,y
SCREEN 9
FOR i=1TO y
FOR j=1TO x
PSET(j*3,i*3),i MOD y<2OR j MOD x<2
NEXT
NEXT

I believe this counts as "not a line." When the MOD expression is false (0), PSET plots a black pixel; when it's true (-1), PSET apparently plots a white pixel. Here's 17,31, shown at 2x size:


答:
Actually, 30 bytes

```<code>;#pXZdX`Σ"67294381";'1+R+íu`Mπ
</code>```

Takes input as a string. Outputs a positive integer for true and 0 for false.

Try it online!

Explanation:

```<code>;#pXZdX`Σ"67294381";'1+R+íu`Mπ
                                 (implicit) push input
;#pXZdx                         push zip(n[:-1], n[1;]) (pairs of digits)
       `Σ"67294381";'1+R+íu`M   map:
        Σ                         join digits
         "67294381";'1+R+         push "16729438183492761" (the magic string used in many other solutions)
                         íu       0-based index (-1 if not found), increment so 0 is not found and >=1 is the 1-based index
                             π  product

</code>```

Title: A Numpad's Knight Numbers

Body:
For the non-zero digits on a standard numpad

```<code>789
456
123
</code>```

consider placing a chess knight at any digit and moving it around with any number of normal L-shaped jumps, tracing out a positive decimal integer. What positive integers can be expressed in such a way?

One of them is 38, since the knight could start on the 3 and move left and up to the 8. 381 and 383 are also possible.

3 itself is possible if no jumps are taken (which is allowed). 5 is as well, but no other digits can be reached from the 5, so it is the only number where the digit 5 appears.

Write a program or function that takes in a positive decimal integer (you may take it as a string if desired) and prints or returns a truthy value if the number can be expressed by a knight on a numpad in the way described, but otherwise outputs a falsy value.

The shortest code in bytes wins. Tiebreaker is earlier answer

Examples

Truthy:

```<code>1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 18, 38, 61, 81, 294, 349, 381, 383, 729, 767, 38183, 38383, 18349276, 183492761, 618349276
</code>```

Falsy:

```<code>10, 11, 50, 53, 55, 65, 95, 100, 180, 182, 184, 185, 186, 187, 188, 189, 209, 305, 2009, 5030, 3838384, 4838383, 183492760
</code>```

Body:
Actually, 30 bytes

;#pXZdX`Σ"67294381";'1+R+íu`Mπ

Takes input as a string. Outputs a positive integer for true and 0 for false.

Try it online!

Explanation:

;#pXZdX`Σ"67294381";'1+R+íu`Mπ
                                 (implicit) push input
;#pXZdx                         push zip(n[:-1], n[1;]) (pairs of digits)
       `Σ"67294381";'1+R+íu`M   map:
        Σ                         join digits
         "67294381";'1+R+         push "16729438183492761" (the magic string used in many other solutions)
                         íu       0-based index (-1 if not found), increment so 0 is not found and >=1 is the 1-based index
                             π  product


问:
Expand a C array
In the C programming language, arrays are defined like this:

```<code>int foo[] = {4, 8, 15, 16, 23, 42};      //Foo implicitly has a size of 6
</code>```

The size of the array is inferred from the initializing elements, which in this case is 6. You can also write a C array this way, explicitly sizing it then defining each element in order:

```<code>int foo[6];        //Give the array an explicit size of 6
foo[0] = 4;
foo[1] = 8;
foo[2] = 15;
foo[3] = 16;
foo[4] = 23;
foo[5] = 42;
</code>```

The challenge

You must write a program or function that expands arrays from the first way to the second. Since you are writing a program to make code longer, and you love irony, you must make your code as short as possible.

The input will be a string representing the original array, and the output will be the expanded array-definition. You can safely assume that the input will always look like this:

```<code><type> <array_name>[] = {<int>, <int>, <int> ... };
</code>```

"Type" and "array_name" will made up entirely of alphabet characters and underscores _. The elements of the list will always be a number in the range -2,147,483,648 to 2,147,483,647. Inputs in any other format do not need to be handled.

The whitespace in your output must exactly match the whitespace in the test output, although a trailing newline is allowed.

Test IO:

```<code>#in
short array[] = {4, 3, 2, 1};

#out
short array[4];
array[0] = 4;
array[1] = 3;
array[2] = 2;
array[3] = 1;

#in
spam EGGS[] = {42};

#out
spam EGGS[1];
EGGS[0] = 42;

#in
terrible_long_type_name awful_array_name[] = {7, -8, 1337, 0, 13};

#out
terrible_long_type_name awful_array_name[5];
awful_array_name[0] = 7;
awful_array_name[1] = -8;
awful_array_name[2] = 1337;
awful_array_name[3] = 0;
awful_array_name[4] = 13;
</code>```

Submissions in any language are encouraged, but bonus points if you can do it in C.

Leaderboard:

Here is a leaderboard showing the top answers:

var QUESTION_ID=77857,OVERRIDE_USER=31716;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
V, 37 Bytes

```<code>2Eé0òYp6ldf ò$dT]ddÎdwf{xwC;
gg"1P
</code>```

V is a 2D, string based golfing language that I wrote, designed off of vim. This works as of commit 17.

Explanation:

This is pretty much a direct translation of my vim answer, albeit significantly shorter.

```<code>2E                               "Move to the end of 2 words forward.
  é0                             "Insert a single '0'
    ò       ò                    "Recursively do:
     Yp6ldf                      "Yank, paste, move 6 right, delete until space.
             $dT]                "Move to the end of line, delete backwards until ']'
                 dd              "Delete this line
                   Î             "Apply the following to every line:
                    dwf{xwC;<\n> "Delete word, move to '{' and delete it, Change to end of line, and enter ';'
</code>```

Then we just have:

```<code>gg"1P     "Move to line 1, and paste buffer '1' behind us.
</code>```

Since this unicode madness can be hard to enter, you can create the file with this reversible hexdump:

```<code>00000000: 3245 e930 f259 7001 366c 6466 20f2 2464  2E.0.Yp.6ldf .$d
00000010: 545d 6464 ce64 7766 7b78 7743 3b0d 6767  T]dd.dwf{xwC;.gg
00000020: 2231 500a                                "1P.
</code>```

This can be run by installing V and typing:

```<code>python main.py c_array.v --f=file_with_original_text.txt
</code>```

Title: Expand a C array

Body:
V, 37 Bytes

2Eé0òYp6ldf ò$dT]ddÎdwf{xwC;
gg"1P

V is a 2D, string based golfing language that I wrote, designed off of vim. This works as of commit 17.

Explanation:

This is pretty much a direct translation of my vim answer, albeit significantly shorter.

2E                               "Move to the end of 2 words forward.
  é0                             "Insert a single '0'
    ò       ò                    "Recursively do:
     Yp6ldf                      "Yank, paste, move 6 right, delete until space.
             $dT]                "Move to the end of line, delete backwards until ']'
                 dd              "Delete this line
                   Î             "Apply the following to every line:
                    dwf{xwC;<\n> "Delete word, move to '{' and delete it, Change to end of line, and enter ';'

Then we just have:

gg"1P     "Move to line 1, and paste buffer '1' behind us.

Since this unicode madness can be hard to enter, you can create the file with this reversible hexdump:

00000000: 3245 e930 f259 7001 366c 6466 20f2 2464  2E.0.Yp.6ldf .$d
00000010: 545d 6464 ce64 7766 7b78 7743 3b0d 6767  T]dd.dwf{xwC;.gg
00000020: 2231 500a                                "1P.

This can be run by installing V and typing:

python main.py c_array.v --f=file_with_original_text.txt


答:
Jelly, <s>50</s> <s>49</s> <s>46</s> <s>43</s> <s>38</s> <s>34</s> <s>33</s> 32 bytes

```<code>Ḥ+ḊZ
>⁶ÇÇFµċ7_ċ4$Ṡị“¤Ỵf“¢*ɦ“¡⁺ƒ»
</code>```

Try it online! or verify all test cases.

Background

There are 16 different 2×2 patterns of blocks and spaces:

```<code>|  |  |  | #|  | #| #|# | #|# |# |##|# |##|##|##|
|  | #|# |  |##| #|# |  |##| #|# |  |##| #|# |##|
</code>```

Of these, since two objects will never touch,

```<code>| #|# |
|# | #|
</code>```

will never occur in the input, leaving us with 14 possible patterns.

Assigning   a value of 0 and # a value of 1, we can encode a 2×2 pattern

```<code>|ab|
|cd|
</code>```

as 2(2a + c) + (2b + d) = 4a + 2b + 2c + d, leaving the following values for the 14 patterns.

```<code>|  |  |  | #|  | #|# | #|# |##|# |##|##|##|
|  | #|# |  |##| #|  |##|# |  |##| #|# |##|
  0  1  2  2  3  3  4  5  6  6  7  7  8  9
</code>```

For partial 2×1, 1×2 or 1×1 patterns at the lower and/or right border, we'll treat them as if the were padded with spaces, encoding them as 4a + 2b, 4a + 2c and 4a, respectively.

This way, each object (soft or hard) will have exactly one 4 pattern (its lower right corner); each soft object will have exactly two 7 patterns (its lower left and its upper right corner).

Thus, subtracting the amount of 4 patterns from the number of 7 patterns encountered in the input will yield (s + h) - 2s = h - s := d, where h and s are the amount of hard and soft objects they form.

We print Hard if d > 0, Soft if d < 0 and Equal if d = 0.

How it works

```<code>Ḥ+ḊZ                         Helper link. Input: M (n×m matrix)

Ḥ                            Unhalve; multiply all entries of M by 2.
  Ḋ                          Dequeue; remove the first row of M.
 +                           Perform vectorized addition.
                             This returns 2 * M[i] + M[i + 1] for each row M[i].
                             Since the M[n] is unpaired, + will not affect it,
                             as if M[n + 1] were a zero vector.
   Z                         Zip; transpose rows with columns.

>⁶ÇÇFµċ7_ċ4$Ṡị“¤Ỵf“¢*ɦ“¡⁺ƒ»  Main link. Input: G (character grid)

>⁶                           Compare each character with ' ', yielding 1 for '#'
                             and 0 for ' '.
  Ç                          Call the helper link.
                             This will compute (2a + c) for each pattern, which is
                             equal to (2b + d) for the pattern to its left.
   Ç                         This yields 2(2a + c) + (2b + d) for each pattern.
    F                        Flatten; collect all encoded patterns in a flat list.

     µ                       Begin a new, monadic link. Argument: A (list)
      ċ7                     Count the amount of 7's.
         ċ4$                 Count the amount of 4's.
        _                    Subtract the latter from the former.
            Ṡ                Yield the sign (1, -1 or 0) of the difference.
              “¤Ỵf“¢*ɦ“¡⁺ƒ»  Yield ['Hard', 'Soft', Equal'] by indexing into a
                             built-in dictionary.
             ị               Retrieve the string at the corresponding index.
</code>```

Body:
Jelly, <s>50</s> <s>49</s> <s>46</s> <s>43</s> <s>38</s> <s>34</s> <s>33</s> 32 bytes

Ḥ+ḊZ
>⁶ÇÇFµċ7_ċ4$Ṡị“¤Ỵf“¢*ɦ“¡⁺ƒ»

Try it online! or <a href="http://jelly.tryitonline.net/#code=4bikK-G4iloKPuKBtsOHw4dGwrXEizdfxIs0JOG5oOG7i-KAnMKk4bu0ZuKAnMKiKsmm4oCcwqHigbrGksK7CsOH4oKsauKBtw&input=&args=WwogWycjIyMjIyMjIyAgICAgICAgICAnLAogICcjICAgICAgIyAgICAgICAgICAnLAogICcjIyMjIyMjIyAgICAgICAgICAnLAogICcgICAgICAgICAgICAgICAgICAnLAogICcgICAjIyMgICAgICAgICMjIyMnLAogICcgICAjIyMgICAgICAgICMjIyMnLAogICcgICAjIyMgICAgICAgICAgICAnXSwKCiBbJyMjIyAgICAgICAgICAgICAgICAnLAogICcjIyMgICAgICAgICAgICAgICAgJywKICAnIyMjICAgICAgICAgICAgICAgICcsCiAgJyAgICAgICAgICAgICAgICAgICAnLAogICcjIyMjIyMjIyMjIyMjIyMjIyMjJywKICAnIyAgICAgICAgICAgICAgICAgIycsCiAgJyMgICAgICAgICAgICAgICAgICMnLAogICcjICAgICAgICAgICAgICAgICAjJywKICAnIyMjIyMjIyMjIyMjIyMjIyMjIyddLAoKIFsnICAgIyMjIyMjICAgICcsCiAgJyAgICMgICAgIyAgICAnLAogICcgICAjIyMjIyMgICAgJywKICAnICAgICAgICAgICMjIycsCiAgJyAgICMjICAjICAjICMnLAogICcgICAgICAgICAgIyMjJywKICAnICAgICAgICAgICAgICcsCiAgJyAgICAgICAgICAgICAnLAogICcgIyMjIyMjIyMgICAgJywKICAnICMgICAgICAjICAgICcsCiAgJyAjIyMjIyMjIyAgICAnXQpd" rel="nofollow">verify all test cases.

Background

There are 16 different 2×2 patterns of blocks and spaces:

|  |  |  | #|  | #| #|# | #|# |# |##|# |##|##|##|
|  | #|# |  |##| #|# |  |##| #|# |  |##| #|# |##|

Of these, since two objects will never touch,

| #|# |
|# | #|

will never occur in the input, leaving us with 14 possible patterns.

Assigning   a value of 0 and # a value of 1, we can encode a 2×2 pattern

|ab|
|cd|

as 2(2a + c) + (2b + d) = 4a + 2b + 2c + d, leaving the following values for the 14 patterns.

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

For partial 2×1, 1×2 or 1×1 patterns at the lower and/or right border, we'll treat them as if the were padded with spaces, encoding them as 4a + 2b, 4a + 2c and 4a, respectively.

This way, each object (soft or hard) will have exactly one 4 pattern (its lower right corner); each soft object will have exactly two 7 patterns (its lower left and its upper right corner).

Thus, subtracting the amount of 4 patterns from the number of 7 patterns encountered in the input will yield (s + h) - 2s = h - s := d, where h and s are the amount of hard and soft objects they form.

We print Hard if d > 0, Soft if d < 0 and Equal if d = 0.

How it works

Ḥ+ḊZ                         Helper link. Input: M (n×m matrix)

Ḥ                            Unhalve; multiply all entries of M by 2.
  Ḋ                          Dequeue; remove the first row of M.
 +                           Perform vectorized addition.
                             This returns 2 * M[i] + M[i + 1] for each row M[i].
                             Since the M[n] is unpaired, + will not affect it,
                             as if M[n + 1] were a zero vector.
   Z                         Zip; transpose rows with columns.

>⁶ÇÇFµċ7_ċ4$Ṡị“¤Ỵf“¢*ɦ“¡⁺ƒ»  Main link. Input: G (character grid)

>⁶                           Compare each character with ' ', yielding 1 for '#'
                             and 0 for ' '.
  Ç                          Call the helper link.
                             This will compute (2a + c) for each pattern, which is
                             equal to (2b + d) for the pattern to its left.
   Ç                         This yields 2(2a + c) + (2b + d) for each pattern.
    F                        Flatten; collect all encoded patterns in a flat list.

     µ                       Begin a new, monadic link. Argument: A (list)
      ċ7                     Count the amount of 7's.
         ċ4$                 Count the amount of 4's.
        _                    Subtract the latter from the former.
            Ṡ                Yield the sign (1, -1 or 0) of the difference.
              “¤Ỵf“¢*ɦ“¡⁺ƒ»  Yield ['Hard', 'Soft', Equal'] by indexing into a
                             built-in dictionary.
             ị               Retrieve the string at the corresponding index.


问:
Shortest infinite loop producing no output
Your task is to create the shortest infinite loop!

The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.

Rules

Each submission must be a full program.

You must create the shortest infinite loop.

Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.

The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.

The program must not write anything to STDERR.

Feel free to use a language (or language version) even if it's newer than this challenge.
-Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. :D

Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.

This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainf**k-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like #[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes.

Standard loopholes are not allowed.

(I have taken some of these rules from Martin Büttner's "Hello World" challenge)

Please feel free to post in the comments to tell me how this challenge could be  improved.

Catalogue

This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:

```<code># Language name, X bytes
</code>```

Obviously replacing Language name and X bytes with the proper items. If you want to link to the languages' website, use this template, as posted above:

```<code>#[Language name](http://link.to/the/language), X bytes
</code>```

Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)

var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"//api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+lang+'').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang,user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase())return 1;if(a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase())return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;width:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
V, 1 byte

```<code>ò
</code>```

V is a 2D string based golfing language that I <s>wrote</s> am in the process of writing, inspired by vim. In vim, recursive macros are a little bit of a pain to set up, so I tried to make them as easy as possible in V. The syntax for a recursive macro is:

```<code>ò<code>ò
</code>```

This is equivalent to

```<code>qq<code>@qq@q
</code>```

in vim.

V will automagically fill in the missing delimiter (in this case, the second ò) so we can leave it off, giving us a nice and simple one-byte solution.

Body:
V, 1 byte

ò

V is a 2D string based golfing language that I <s>wrote</s> am in the process of writing, inspired by vim. In vim, recursive macros are a little bit of a pain to set up, so I tried to make them as easy as possible in V. The syntax for a recursive macro is:

ò<code>ò

This is equivalent to

qq<code>@qq@q

in vim.

V will automagically fill in the missing delimiter (in this case, the second ò) so we can leave it off, giving us a nice and simple one-byte solution.


Title: A Numpad's Knight Numbers

Body:
C, <s>140</s> 92 bytes

c;L(char*i){while(*i&&(!c||*i=="6743x1212"[c-49]||*i=="8989x7634"[c-49]))c=*i++;return !*i;}

Assuming ASCII

Detailed Try it here

// valid transition from x to n[x-'1'][0 or 1]

int n[9][2] =
{
    {'6','8'},{'7','9'},{'4','8'},
    {'3','9'},{'x','x'},{'1','7'},
    {'2','6'},{'1','3'},{'2','4'}
};

// i is a pointer to where to start on a string

bool L(char * i)
{
    char c = 0;

    // move if not \0 and (not-first-char or is a valid move)

    while((*i) && (!c || (*i)==n[c-'1'][0] || (*i)==n[c-'1'][1]))
    {
        c = (*i++);
    }

    return !(*i); // success if it's \0
}


问:
Josephus problem with three inputs
There's a question on this site that is similar to this question, but I have added a twist.

You have three inputs, the number of people in the circle n, the k-th person counted out at each step, and the q-th person that survives. The people in the circle are numbered 1 to n.

For example, in a circle of 20 people, the 20th person to survive is the very first person removed, the 19th survivor is the second person removed and so on. Normally, the Josephus problem is to determine the last person removed, here called the first survivor.

Write the shortest program or function that, with those three inputs, returns the number of the q-th person to survive.

If there are any issues with clarity, please let me know.

Some examples:

```<code>>>> josephus(20, 3, 9)
4
>>> josephus(4, 3, 1)
1
>>> josephus(100, 9, 12)
46
</code>```

Edit: Assume all inputs are valid. That is no one will ask for 0 or any negative numbers and no one will ask for the 20th survivor in a circle of 5 people (that is, 1 ≤ q ≤ n)

Edit: I'll accept an answer at midnight UTC+7 at the start of December 2.

答:
Haskell, <s>48</s> <s>47</s> 43 bytes

```<code>(n!k)q=1+foldl(mod.(k+))(mod(k-1)q)[q+1..n]
</code>```

Based on a Haskell algorithm on the Rosetta Code page of the Josephus function with two inputs. Golfing suggestions are welcome.

Edit: My thanks to nimi for help with golfing the first algorithm via suggesting a pointfree version, and for help with golfing the second algorithm by letting me know that the until keyword exists.

```<code>(n#k)q|m<-k-1=1+n*k-until(>n*m)(\z-> -div(-z*k)m)(q*k-mod m q)
</code>```

A version of the algorithm at the end of my Python answer adapted from Concrete Mathematics by Graham, Knuth and Patashnik. Though this algorithm is longer at 62 bytes, and has not been golfed down as much as the first, it is faster for large n and small k.

Ungolfed:

First algorithm

```<code>jos_g num step q = 1 + foldl (\x -> mod (x + step) ) (mod (step-1) q) [q+1..num]
</code>```

Second algorithm

```<code>jos_gkp num step q
    -- ceiling throws a type-related fit with ceiling(z*k/(k-1))
    -- better to use - div (-z * k) (k - 1)
    | m <- step-1 = 1 + num*step - until (>num*m)(\z-> -div (-z*k) m) (q*step - mod m q)
</code>```

Title: Josephus problem with three inputs

Body:
Haskell, <s>48</s> <s>47</s> 43 bytes

(n!k)q=1+foldl(mod.(k+))(mod(k-1)q)[q+1..n]

Based on a Haskell algorithm on the Rosetta Code page of the Josephus function with two inputs. Golfing suggestions are welcome.

Edit: My thanks to nimi for help with golfing the first algorithm via suggesting a pointfree version, and for help with golfing the second algorithm by letting me know that the until keyword exists.

(n#k)q|m<-k-1=1+n*k-until(>n*m)(\z-> -div(-z*k)m)(q*k-mod m q)

A version of the algorithm at the end of my Python answer adapted from Concrete Mathematics by Graham, Knuth and Patashnik. Though this algorithm is longer at 62 bytes, and has not been golfed down as much as the first, it is faster for large n and small k.

Ungolfed:

First algorithm

jos_g num step q = 1 + foldl (\x -> mod (x + step) ) (mod (step-1) q) [q+1..num]

Second algorithm

jos_gkp num step q
    -- ceiling throws a type-related fit with ceiling(z*k/(k-1))
    -- better to use - div (-z * k) (k - 1)
    | m <- step-1 = 1 + num*step - until (>num*m)(\z-> -div (-z*k) m) (q*step - mod m q)


问:
Solve a quadratic equation using Vieta's formulas

Exposition

Your mathematics teacher is a big fan of Vieta's formulas, and he believes that you should use them to solve quadratic equations. Given the equation

```<code>ax^2 + bx + c = 0
</code>```

the product of its roots is c/a, and their sum is -b/a. When all of a, b and c are nonzero integers, assuming the roots are rational numbers, it's enough to try all possible numbers in the form

```<code>r1 = ±s/t
</code>```

where s is a divisor of abs(c), and t is a divisor of abs(a). For each such r1, plug it into ax^2 + bx + c, and see whether the result is 0. If yes, then r1 is a root. The second root is -b/a-r1 or (c/a)/r1 - you can choose whatever formula you like.

Your teacher decided to give you many exercises, and he expects you to describe how you used Vieta's formulas to solve each one. Each exercise looks like this (example):

```<code>9x^2+12x+4=0
</code>```

Write a subroutine or a program that gets an exercise as input, and outputs your alleged "solving process" to appease your teacher.

Input

Since you will feed the exercise to your program manually, format it in any convenient form. For example, use space-separated values on stdin:

```<code>9 12 4
</code>```

or call a function with 3 parameters:

```<code>SolveExercise(9, 12, 4);
</code>```

or parse the exercise literally:

```<code>9x^2+12x+4=0
</code>```

Your output should be formatted as described below. Use the standard output device or return it as a string from your subroutine.

Output (example)

```<code>x = 1? 9x^2+12x+4 = 25
x = 2? 9x^2+12x+4 = 64
x = 1/3? 9x^2+12x+4 = 9
x = 2/3? 9x^2+12x+4 = 16
... (as many or as few failed attempts as you like)
x = -2/3? 9x^2+12x+4 = 0
r1 = -2/3
r2 = -12/9-(-2/3) = -2/3
</code>```

Alternatively, the last line can be:

```<code>r2 = 4/9/(-2/3) = -2/3
</code>```

Some additional notes:

The minimum number of line-breaks in the output is as described in the example (trailing line-break is not required). Additional line-breaks are permitted.

All coefficients in input are integers in the range [-9999...9999], none can be equal to 0

All roots are rational numbers, and should be output as such - e.g. 0.66666667 is not equal to 2/3 and so is incorrect

In the final expressions for r1 and r2, integers should be output as such, e.g. -99/1 is unacceptable, and should be output as -99; in other places in the output, denominator equal to ±1 is acceptable

Reduced form for rational numbers is not required - e.g. 2/4 is a good substitute for 1/2, even though it's ugly, even for roots r1 and r2

Parentheses in the output are sometimes required by rules of mathematics, e.g. in the expression 12/9/(2/3). When precedence rules of mathematics permit omission of parentheses, they are not required, e.g. -12/9--2/3. Superfluous parentheses are permitted: 4-(2) is OK, even though it's ugly

There should be at least one case (input) for which your program tries 3 or more non-integer values for r1; however, it's allowed to "guess the right answer" almost always on the first try

All trial values for r1 must be rational numbers ±s/t, where s and t are constrained as described above

Test cases

Input

```<code>x^2-x-2=0
</code>```

or

```<code>1 -1 -2
</code>```

Possible output

```<code>r1 = ±s/t
</code>```0

Input

```<code>r1 = ±s/t
</code>```1

or

```<code>r1 = ±s/t
</code>```2

Possible output

```<code>x=1? -x^2+2x-1=0
r1=1
r2=-2/-1-1=1
</code>```

Input

```<code>7x^2-316x+924=0
</code>```

or

```<code>X(7, -316, 924);
</code>```

Possible output (a divisor of 924 is 42, which solves the equation by "luck")

```<code>x=42? 7x^2-316x+924=0
r1=42
r2=316/7-42=22/7
</code>```

Input

```<code>6x^2-35x-6=0
</code>```

or

```<code>[6 -35 -6]
</code>```

Possible output (even though your program may "know" that 6 is a root, it decides to show some failed trials)

```<code>x=1/2? 6x^2-35x-6=-88/4
x=1/3? 6x^2-35x-6=-153/9
x=3/2? 6x^2-35x-6=-180/4
x=6/1? 6x^2-35x-6=0
r1=6
r2=35/6-6=-1/6
</code>```

Alternative versions for the last line:

```<code>9x^2+12x+4=0
</code>```0

Impossible input (no rational solutions)

```<code>9x^2+12x+4=0
</code>```1

Impossible input (zero coefficient)

```<code>9x^2+12x+4=0
</code>```2

Body:
JavaScript (ES6), 373

(a,b,c,z='',A=Math.abs,M=(c,x,a)=>'-+'[c>0|0]+(x&&a<2?x:a+x),G=(a,b)=>b?G(b,a%b):a,O=(n,d,g=G(n,d))=>(g=d*g<0?-g:g)-d?n/g+'/'+d/g:n/d,e=M(a,'x^2',o=A(a))+M(b,'x',A(b))+M(c,'',q=A(c)),K=s=>(z+=`
x=${s}/${t}? ${e}=`+(v=a*s*s+b*s*t+c*t*t)+(v?'':`
r1=${O(s,t)}
r2=(${c}/${a})/(${s}/${t})=`+O(c*t,s*a)),v))=>{for(s=0;++s<=q;)for(t=0;++t<=o;)if(!(q%s||o%t||K(-s)&&K(s)))return z}

Test

f=(a,b,c,z='',A=Math.abs,M=(c,x,a)=>'-+'[c>0|0]+(x&&a<2?x:a+x),G=(a,b)=>b?G(b,a%b):a,O=(n,d,g=G(n,d))=>(g=d*g<0?-g:g)-d?n/g+'/'+d/g:n/d,e=M(a,'x^2',o=A(a))+M(b,'x',A(b))+M(c,'',q=A(c)),K=s=>(z+=`
x=${s}/${t}? ${e}=`+(v=a*s*s+b*s*t+c*t*t)+(v?'':`
r1=${O(s,t)}
r2=(${c}/${a})/(${s}/${t})=`+O(c*t,s*a)),v))=>{for(s=0;++s<=q;)for(t=0;++t<=o;)if(!(q%s||o%t||K(-s)&&K(s)))return z}

// Less golfed
U=(a,b,c,
   // locals
   z='',
   A=Math.abs,
   M=(c,x,a)=>'-+'[c>0|0]+(x&&a<2?x:a+x),
   G=(a,b)=>b?G(b,a%b):a, // GCD
   O=(n,d,g=G(n,d))=>(g=d*g<0?-g:g)-d?n/g+'/'+d/g:n/d, // output a fraction
   o=A(a),q=A(c),
   e=M(a,'x^2',o)+M(b,'x',A(b))+M(c,'',q), // espression from coefficients
   K=s=>( // check & output a candidate solution
      z+=`\nx=${s}/${t}? ${e}=`+(v=a*s*s+b*s*t+c*t*t)+(v?'':`
r1=${O(s,t)}
r2=(${c}/${a})/(${s}/${t})=`+O(c*t,s*a)),v
  )
)=>{
  for(s=0;++s<=q;)
    for(t=0;++t<=o;)
      if(!(q%s||o%t||K(-s)&&K(s)))
        return z
}

console.log=x=>O.textContent+=x+'\n'

// Test
console.log(f(9,12,4))
console.log(f(1,-1,-2))
console.log(f(-1,2,-1))
console.log(f(7,-316,924))
console.log(f(6,-35,-6))

<pre id=O></pre>


问:
Sequential Multiplication
Your objective is to write a program that takes an input, and, when chained together N times, performs "sequential multiplication". What is sequential multiplication, you may ask? It's a sequence with a seed a defined as thus:

```<code>f(0) = a
f(n+1) = f(n)*(f(n)-1)
</code>```

So, let a = 5. Thus, f(0) = 5, f(1) = f(0)*(f(0)-1) = 5*4 = 20, and f(2) = f(1)*(f(1)-1) = 20*19 = 380.

If your program was ABC, then ABC should take input a and output f(1). Program ABCABC should output f(2), etc. Your program series should only take input once and only output once.

This is a code-golf so the shortest program in bytes wins. Standard loopholes are banned.

答:
Mathcad, 39 "bytes"

From user perspective, Mathcad is effectively a 2D whiteboard, with expressions evaluated from left-to-right,top-to-bottom. Mathcad does not support a conventional "text" input, but instead makes use of a combination of text and special keys / toolbar / menu items to insert an expression, text, plot or component. For example, type ":" to enter the definition operator (shown on screen as ":="), "[" to enter an array index, or "ctl-]" to enter a while loop operator (inclusive of placeholders for the controlling condition and one body expression). What you see in the image above is exactly what appears on the user interface and as "typed" in.

For golfing purposes, the "byte" count is the equivalent number of keyboard operations required to enter an expression.

One thing I'm even less sure about (from an "byte" equivalence point of view) is how to count creating a new region  (eg, a:=5 or k:=0..n-1).  I've equated each move to a new region as being equal to a newline, and hence 1 byte (in practice, I use the mouse to click where I want the region).

I've only included the active statements and not the comments, and I've included 2 bytes each for the a and n inputs but not the values themselves (5 and 7 in the example).

Title: Sequential Multiplication


问:
Numbers with Rotational Symmetry
Given an integer, output a truthy value if it is the same upside-down (rotated 180°) or a falsy value otherwise.

0, 1, and 8 have rotational symmetry. 6 becomes 9 and vice versa.

Sequence of numbers producing truthy results: OEIS A000787

```<code>0, 1, 8, 11, 69, 88, 96, 101, 111, 181, 609, 619, 689, 808, 818, 888, 906, 916, 986, 1001, 1111, 1691, 1881, 1961, 6009, 6119, 6699, 6889, 6969, 8008, 8118, 8698, 8888, 8968, 9006, 9116, 9696, 9886, 9966, 10001, 10101, 10801, 11011, 11111, 11811, 16091, ...
</code>```

This question is inspired by my own reputation at the time of posting: 6009.

答:
C, 73 <s>82</s> bytes

f(x){int y=0,z=x;for(;x;x/=10)y=y*10+"0100009086"[x%10]-'0';return z==y;}
```
<h2>Expanded</h2>
<pre class="lang-c prettyprint-override"><code>static const char s[] = "0100009086";
int f(int x)
{
    int y=0, z=x;
    for(; x; x/=10)
        y = y*10 + s[x%10]-'0';
    return z==y;
}
</code>```

Explanation

We reverse the digits of x using modulo-10 arithmetic, replacing 6 and 9 by their reflections as we go.  We replace the rotationally-asymmetric digits by zeros (note that we can handle symmetric fives and/or twos by simply changing the replacement table s).  If the new number is equal to the original (saved in 'z'), then it is rotationally symmetric.

Test program

#include <stdio.h>
int main()
{
    int i;
    for(i=0;  i <= 16091; ++i)
        if (f(i))
            printf("%d\n", i);
}
```

This prints the list of symmetric numbers given in the question.

ContentLicense: CC BY-SA 4.0

Title: Numbers with Rotational Symmetry

Body:
C, 73 <s>82</s> bytes

f(x){int y=0,z=x;for(;x;x/=10)y=y*10+"0100009086"[x%10]-'0';return z==y;}

Expanded

static const char s[] = "0100009086";
int f(int x)
{
    int y=0, z=x;
    for(; x; x/=10)
        y = y*10 + s[x%10]-'0';
    return z==y;
}

Explanation

We reverse the digits of x using modulo-10 arithmetic, replacing 6 and 9 by their reflections as we go.  We replace the rotationally-asymmetric digits by zeros (note that we can handle symmetric fives and/or twos by simply changing the replacement table s).  If the new number is equal to the original (saved in 'z'), then it is rotationally symmetric.

Test program

#include <stdio.h>
int main()
{
    int i;
    for(i=0;  i <= 16091; ++i)
        if (f(i))
            printf("%d\n", i);
}

This prints the list of symmetric numbers given in the question.


答:
MATL, <s>3</s> 2 bytes

Quite simple really:

```<code>`T

`    # Do ... while
 T   # True
     # Implicit end, normally: ]
</code>```

Try it online here (Please stop it after testing, don't keep it running).

Title: Shortest infinite loop producing no output

Body:
Your task is to create the shortest infinite loop!

The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.

Rules

Each submission must be a full program.

You must create the shortest infinite loop.

Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.

The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.

The program must not write anything to STDERR.

Feel free to use a language (or language version) even if it's newer than this challenge.
-Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. :D

Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.

This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainf**k-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like #[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes.

Standard loopholes are not allowed.

(I have taken some of these rules from Martin Büttner's "Hello World" challenge)

Please feel free to post in the comments to tell me how this challenge could be  improved.

Catalogue

This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:

```<code># Language name, X bytes
</code>```

Obviously replacing Language name and X bytes with the proper items. If you want to link to the languages' website, use this template, as posted above:

```<code>#[Language name](http://link.to/the/language), X bytes
</code>```

Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)

var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"//api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+lang+'').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang,user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase())return 1;if(a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase())return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;width:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
MATL, <s>3</s> 2 bytes

Quite simple really:

`T

`    # Do ... while
 T   # True
     # Implicit end, normally: ]

Try it online here (Please stop it after testing, don't keep it running).


答:
Python, 188 <s>194</s>

-6 bytes from getting rid of some whitespace

This challenge brought me back to when I was first learning to program...

```<code>def f(x,s=zip("M CM D CD C XC L XL X IX V IV I".split(),[1e3,900,500,400,100,90,50,40,10,9,5,4,1])):
 r=""if x<4e3else"("+f(x/1e3)+")";x%=1e3
 for a,b in s:
    while x>=b:r+=a;x-=b
 return r
</code>```

It might not be the shortest solution, but I had fun golfing this problem.

Try it out!

Title: Convert to Roman Numeral!

Body:
Your task is to convert a given positive integer from Arabic numeral to Roman numeral.

Things get difficult when you count to 4000.

The romans did this by adding a line above a symbol to multiply that symbol by 1 000. However, overlines aren't exactly displayable in ASCII. Also, there are double overlines to multiply a symbol by 1 000 000, and then triple overline to multiply a symbol by 1 000 000 000, etc...

Therefore, I decided to use parentheses to replace overlines.

The symbols can be individually placed in parentheses. For example, both (VI) and (V)(I) are valid representations of 6 000. (V)M is also a valid representation of 6000.

(I) is a valid way to represent 1 000.

Testcases

```<code>Input: 1
Output: I
Input: 2
Output: II
Input: 3
Output: III
Input: 4
Output: IV
Input: 15
Output: XV
Input: 40
Output: XL
Input: 60
Output: LX
Input: 67
Output: LXVII
Input: 400
Output: CD
Input: 666
Output: DCLXVI
Input: 3000
Output: MMM
Input: 3999
Output: MMMCMXCIX
Input: 4000
Output: M(V)
Input: 4999
Output: M(V)CMXCIX
Input: 6000
Output: (VI)
Input: 6000000
Output: ((VI))
Input: 6006000
Output: ((VI)VI)
Input: 6666666666
Output: (((VI)DCLXVI)DCLXVI)DCLXVI
</code>```

Scoring

This is code-golf. Shortest code in bytes win.

Body:
Python, 188 <s>194</s>

-6 bytes from getting rid of some whitespace

This challenge brought me back to when I was first learning to program...

def f(x,s=zip("M CM D CD C XC L XL X IX V IV I".split(),[1e3,900,500,400,100,90,50,40,10,9,5,4,1])):
 r=""if x<4e3else"("+f(x/1e3)+")";x%=1e3
 for a,b in s:
    while x>=b:r+=a;x-=b
 return r

It might not be the shortest solution, but I had fun golfing this problem.

Try it out!


问:
Josephus problem (counting out)

The challenge

Write a function that takes two positive integers \$n\$ and \$k\$ as arguments and returns the number of the last person remaining out of \$n\$ after counting out each \$k\$-th person.

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

The problem

\$n\$ people (numbered from \$1\$ to \$n\$) are standing in a circle and each \$k\$-th is counted out until a single person is remaining (see the corresponding wikipedia article). Determine the number of this last person.

E.g. for \$k=3\$ two people will be skipped and the third will be counted out. I.e. for \$n=7\$ the numbers will be counted out in the order \$3 \, 6 \, 2 \, 7 \, 5 \, 1\$ (in detail \$\require{cancel}1 \, 2 \, \cancel{3} \, 4 \, 5 \, \cancel{6} \, 7 \, 1 \, \cancel{2} \, 4 \, 5 \, \cancel{7} \, 1 \, 4 \, \cancel{5} \, 1 \, 4 \, \cancel{1} \, 4\$) and thus the answer is \$4\$.

Examples

```<code>J(7,1) = 7      // people are counted out in order 1 2 3 4 5 6 [7]
J(7,2) = 7      // people are counted out in order 2 4 6 1 5 3 [7]
J(7,3) = 4      // see above
J(7,11) = 1
J(77,8) = 1
J(123,12) = 21
</code>```

答:
C++, 166 bytes

Golfed:

#include<iostream>
#include <list>
int j(int n,int k){if(n>1){return(j(n-1,k)+k-1)%n+1;}else{return 1;}}
int main(){intn,k;std::cin>>n>>k;std::cout<<j(n,k);return 0;}
```

<h3>Ungolfed:</h3>

<pre class="lang-cpp prettyprint-override"><code>#include<iostream>
#include <list>
int j(int n,int k){
    if (n > 1){
        return (j(n-1,k)+k-1)%n+1;
    } else {
        return 1;
    }
}
int main()
{
    int n, k;
    std::cin>>n>>k;
    std::cout<<j(n,k);
    return 0;
}
</code>```

Title: Josephus problem (counting out)

Body:
C++, 166 bytes

Golfed:

#include<iostream>
#include <list>
int j(int n,int k){if(n>1){return(j(n-1,k)+k-1)%n+1;}else{return 1;}}
int main(){intn,k;std::cin>>n>>k;std::cout<<j(n,k);return 0;}

Ungolfed:

#include<iostream>
#include <list>
int j(int n,int k){
    if (n > 1){
        return (j(n-1,k)+k-1)%n+1;
    } else {
        return 1;
    }
}
int main()
{
    int n, k;
    std::cin>>n>>k;
    std::cout<<j(n,k);
    return 0;
}