Title: Variable Prime "Twins"

Body:
Java 7, <s>185</s> 175 bytes

import java.util.*;List c(int k,int u){List l=new ArrayList();for(int i=1;++i<u;)if(p(i)&p(i+k))l.add(i);return l;}boolean p(int n){for(int i=2;i<n;)n=n%i++<1?0:n;return n>1;}

Ungolfed & test code:

Try it here.

import java.util.*;
class M{
  static List c(int k, int u){
    List l = new ArrayList();
    for(int i = 1; ++i < u; ){
      if(p(i) & p(i+k)){
        l.add(i);
      }
    }
    return l;
  }

  static boolean p(int n){
    for(int i = 2; i < n; ){
      n = n % i++ < 1
           ? 0
           : n;
    }
    return n>1;
  }

  public static void main(String[] a){
    System.out.println(c(12, 1000));
    System.out.println(c(2, 999));
    System.out.println(c(3, 1500));
    System.out.println(c(30, 1500));
  }
}

Output:

[5, 7, 11, 17, 19, 29, 31, 41, 47, 59, 61, 67, 71, 89, 97, 101, 127, 137, 139, 151, 167, 179, 181, 199, 211, 227, 229, 239, 251, 257, 269, 271, 281, 337, 347, 367, 389, 397, 409, 419, 421, 431, 449, 467, 479, 487, 491, 509, 557, 587, 601, 607, 619, 631, 641, 647, 661, 727, 739, 757, 761, 797, 809, 811, 827, 907, 929, 941, 971, 997]
[3, 5, 11, 17, 29, 41, 59, 71, 101, 107, 137, 149, 179, 191, 197, 227, 239, 269, 281, 311, 347, 419, 431, 461, 521, 569, 599, 617, 641, 659, 809, 821, 827, 857, 881]
[2]
[7, 11, 13, 17, 23, 29, 31, 37, 41, 43, 53, 59, 67, 71, 73, 79, 83, 97, 101, 107, 109, 127, 137, 149, 151, 163, 167, 181, 193, 197, 199, 211, 227, 233, 239, 241, 251, 263, 277, 281, 283, 307, 317, 337, 349, 353, 359, 367, 379, 389, 401, 409, 419, 431, 433, 449, 457, 461, 479, 491, 541, 547, 557, 563, 569, 571, 577, 587, 601, 613, 617, 631, 643, 647, 653, 661, 709, 727, 739, 743, 757, 797, 809, 823, 827, 829, 853, 857, 877, 881, 907, 911, 937, 941, 947, 953, 967, 983, 991, 1009, 1019, 1021, 1031, 1033, 1039, 1061, 1063, 1087, 1093, 1123, 1151, 1163, 1171, 1187, 1193, 1201, 1229, 1249, 1259, 1277, 1289, 1291, 1297, 1399, 1409, 1423, 1429, 1451, 1453, 1459, 1481, 1493]


问:
Exploded view of a string
Don't you love those exploded-view diagrams  in which a machine or object is taken apart into its smallest pieces?

Let's do that to a string!

The challenge

Write a program or function that

inputs a string containing only printable ASCII characters;

dissects the string into groups of non-space equal characters (the "pieces" of the string);

outputs those groups in any convenient format, with some separator between groups.

For example, given the string

```<code>Ah, abracadabra!
</code>```

the output would be the following groups:

```
!
,
A
aaaaa
bb
c
d
h
rr
```

Each group in the output contains equal characters, with spaces removed. A newline has been used as separator between groups. More about allowed formats below.

Rules

The input should be a string or an array of chars. It will only contain printable ASCII chars (the inclusive range from space to tilde). If your language does not support that, you can take the input in the form of numbers representing ASCII codes.

You can assume that the input contains at least one non-space character.

The output should consist of characters (even if the input is by means of ASCII codes). There has to be an unambiguous separator between groups, different than any non-space character that may appear in the input.

If the output is via function return, it may also be an array or strings, or an array of arrays of chars, or similar structure. In that case the structure provides the necessary separation.

A separator between characters of each group is optional. If there is one, the same rule applies: it can't be a non-space character that may appear in the input. Also, it can't be the same separator as used between groups.

Other than that, the format is flexible. Here are some examples:

The groups may be strings separated by newlines, as shown above.

The groups may be separated by any non-ASCII character, such as  ¬. The output for the above input would be the string:

```<code>!¬,¬A¬aaaaa¬bb¬c¬d¬h¬rr
</code>```

The groups may be separated by n>1 spaces (even if n is variable), with chars between each group separated by a single space:

```<code>!  ,    A   a a a a a    b b  c       d   h  r r
</code>```

The output may also be an array or list of strings returned by a function:

```<code>['!', 'A', 'aaaaa', 'bb', 'c', 'd', 'h', 'rr']
</code>```

Or an array of char arrays:

```<code>[['!'], ['A'], ['a', 'a', 'a', 'a', 'a'], ['b', 'b'], ['c'], ['d'], ['h'], ['r', 'r']]
</code>```

Examples of formats that are not allowed, according to the rules:

A comma can't be used as separator (!,,,A,a,a,a,a,a,b,b,c,d,h,r,r), because the input may contain commas.

It's not accepted to drop the separator between groups (!,Aaaaaabbcdhrr) or to use the same separator between groups and within groups (! , A a a a a a b b c d h r r).

The groups may appear in any order in the output. For example: alphabetical order (as in the examples above), order of first appearance in the string, ... The order need not be consistent or even deterministic.

Note that the input cannot contain newline characters, and A and a are different characters (grouping is case-sentitive).

Shortest code in bytes wins.

Test cases

In each test case, first line is input, and the remaining lines are the output, with each group in a different line.

Test case 1:

```
Ah, abracadabra!
!
,
A
aaaaa
bb
c
d
h
rr
```

Test case 2:

```
\o/\o/\o/
///
\\\
ooo
```

Test case 3:

```
A man, a plan, a canal: Panama!
!
,,
:
A
P
aaaaaaaaa
c
ll
mm
nnnn
p
```

Test case 4:

```
"Show me how you do that trick, the one that makes me scream" she said
""
,
S
aaaaa
cc
dd
eeeeeee
hhhhhh
ii
kk
mmmm
n
ooooo
rr
ssss
tttttt
u
ww
y
```

答:
Common Lisp, 123

```<code>(lambda(s &aux(w(string-trim" "(sort s'char<))))(princ(elt w 0))(reduce(lambda(x y)(unless(char= x y)(terpri))(princ y))w))
</code>```

Ungolfed:

```<code>(lambda (s &aux (w (string-trim " " (sort s 'char<))))
  (princ (elt w 0))
  (reduce
    (lambda (x y)
      (unless (char= x y) (terpri))
      (princ y))
  w))
</code>```

Not the most golf friendly language. This could probably be modified to return list of lists instead of printing string.

ContentLicense: CC BY-SA 3.0

Title: Exploded view of a string

Body:
Common Lisp, 123

(lambda(s &aux(w(string-trim" "(sort s'char<))))(princ(elt w 0))(reduce(lambda(x y)(unless(char= x y)(terpri))(princ y))w))

Ungolfed:

(lambda (s &aux (w (string-trim " " (sort s 'char<))))
  (princ (elt w 0))
  (reduce
    (lambda (x y)
      (unless (char= x y) (terpri))
      (princ y))
  w))

Not the most golf friendly language. This could probably be modified to return list of lists instead of printing string.


问:
Smallest palindrome divisible by the input
Given a positive integer N, output the smallest positive integer such that this number is a palindrome (i.e. is its own reverse) and is divisible by N.

The palindrome (i.e. the output) must not need a leading zero to be a palindrome, e.g. 080 is not the valid answer for 16.

The input will never be a multiple of 10, because of the previous reason.

Your program may take as much time as necessary, even if in practice it would be way too long to output the answer.

Inputs and outputs

You may take the input through STDIN, as a function argument, or anything similar.

You may print the output to STDOUT, return it from a function, or anything similar.

Inputs and outputs must be in the decimal base.

Test cases

```<code>N        Output
1        1
2        2
16       272
17       272
42       252
111      111
302      87278
1234     28382
</code>```

Scoring

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

答:
MATL, 10 bytes

```<code>0`G+tVtP<a
</code>```

Try it online!

```<code>0      % Push 0
`      % Do...while
  G+   %   Add the input. This generates the next multiple of the input
  tV   %   Duplicate, convert to string
  tP   %   Duplicate, reverse
  <a   %   Is any digit lower than the one in the reverse string? This is the
       %   loop condition: if true, the loop proceeds with the next iteration
       % End do...while
       % Implicitly display
</code>```

Body:
MATL, 10 bytes

0`G+tVtP<a

Try it online!

0      % Push 0
`      % Do...while
  G+   %   Add the input. This generates the next multiple of the input
  tV   %   Duplicate, convert to string
  tP   %   Duplicate, reverse
  <a   %   Is any digit lower than the one in the reverse string? This is the
       %   loop condition: if true, the loop proceeds with the next iteration
       % End do...while
       % Implicitly display


答:
PARI/GP, 39 bytes

```<code>k->u->[x|x<-primes([1,u]),isprime(x+k)]
</code>```

Title: Variable Prime "Twins"

Body:
I am 2/3 twins with my brother, i.e. born on the same day of the same month but twelve years later. When I was 5, he was 17, both primes; the last pair of ages we can reasonably count on is [71, 83] with both of us being alive and able to celebrate this coincidental jubilee.

Task

Create a code that

takes two integers as input: the difference between the counter and the "twin" as a positive integer k (well yes, I'm the younger) and the upper bound as a positive integer u (runtime consideration)

and gives output as an array or list of all i numbers lower than or equal u for which both i and i+k are primes. The output does not need to be sorted.

Test Cases

```<code>12, 1000 -> [5, 7, 11, 17, 19, 29, 31, 41, 47, 59, 61, 67, 71, 89, 97, 101, 127, 137, 139, 151, 167, 179, 181, 199, 211, 227, 229, 239, 251, 257, 269, 271, 281, 337, 347, 367, 389, 397, 409, 419, 421, 431, 449, 467, 479, 487, 491, 509, 557, 587, 601, 607, 619, 631, 641, 647, 661, 727, 739, 757, 761, 797, 809, 811, 827, 907, 929, 941, 971, 997]
2, 999 -> [3, 5, 11, 17, 29, 41, 59, 71, 101, 107, 137, 149, 179, 191, 197, 227, 239, 269, 281, 311, 347, 419, 431, 461, 521, 569, 599, 617, 641, 659, 809, 821, 827, 857, 881]
3, 1500 -> [2]
30, 1500 -> [7, 11, 13, 17, 23, 29, 31, 37, 41, 43, 53, 59, 67, 71, 73, 79, 83, 97, 101, 107, 109, 127, 137, 149, 151, 163, 167, 181, 193, 197, 199, 211, 227, 233, 239, 241, 251, 263, 277, 281, 283, 307, 317, 337, 349, 353, 359, 367, 379, 389, 401, 409, 419, 431, 433, 449, 457, 461, 479, 491, 541, 547, 557, 563, 569, 571, 577, 587, 601, 613, 617, 631, 643, 647, 653, 661, 709, 727, 739, 743, 757, 797, 809, 823, 827, 829, 853, 857, 877, 881, 907, 911, 937, 941, 947, 953, 967, 983, 991, 1009, 1019, 1021, 1031, 1033, 1039, 1061, 1063, 1087, 1093, 1123, 1151, 1163, 1171, 1187, 1193, 1201, 1229, 1249, 1259, 1277, 1289, 1291, 1297, 1399, 1409, 1423, 1429, 1451, 1453, 1459, 1481, 1493]
</code>```

Edit

Since I failed to specify the upper bound, both inclusive and exclusive solutions are welcome.

Edit No. 2

The challenge ends on 1st September, one week from the start.

Looks like we have a winner but in case of a tie popularity is the tie-breaker; in this case the "second" will be compensated via bounty.

Body:
PARI/GP, 39 bytes

k->u->[x|x<-primes([1,u]),isprime(x+k)]


问:
Divide a number by 3 without using *, /, +, -, % operators
Quoting this question on SO (Spoiler alert!):

This question has been asked in an Oracle interview.

How would you divide a number by 3 without using *, /, +, -, %,
  operators?

The number may be signed or unsigned.

The task is solvable, but see if you can write the shortest code.

Rules:

Perform the required integer division (/3)

Do not use the non-text-based operators *, /, +, -, or % (or their equivalents, such as __div__ or add()). This also applies to incrementing and decrementing operators, like i++ or i--. Use of operators for string concatenation and formatting are OK. Using these characters for different operators, such as unary - operator for negative numbers, or * to represent a pointer in C is OK as well.

Input value can be arbitrarily large (whatever your system can handle), both positive and negative

Input can be on STDIN or ARGV or entered any other way

Create the shortest code you can to do the above

答:
Perl using an eval to compute a string version of x/3.

Perl 5.8 Version

```<code>print eval join' ','int',$ARGV[0],map{chr}47,51
</code>```

Perl 5.10 Version

```<code>say print eval join' ','int',$ARGV[0],map{chr}47,51
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Perl using an eval to compute a string version of x/3.

Perl 5.8 Version

print eval join' ','int',$ARGV[0],map{chr}47,51

Perl 5.10 Version

say print eval join' ','int',$ARGV[0],map{chr}47,51


答:
Emacs, 36 keystrokes

C-SPACE C-EM-xsort-rTABRETURN.RETURN.RETURNC-AC-M-S-%\(\(.\)\2*\)RETURN\1C-QC-JRETURN!

Result

A man, a plan, a canal: Panama! -->

```<code>!
,,
:
A
P
aaaaaaaaa
c
ll
mm
nnnn
p
</code>```

Explanation

C-SPACE C-E

M-x sort-rTAB RETURN .RETURN .RETURN

C-A

C-M-S-% \(\(.\)\2*\)RETURN\1 C-Q C-JRETURN !

Select the input line;

Call sort-regexp-fields with arguments . and .;

Argument #1: Regexp scpecifying records to sort

Argument #2: Regexp scpecifying key within records

Return at line start;

Apply regexp substitution \(\(.\)\2*\) -> \1\n on all matches.

Title: Exploded view of a string

Body:
Don't you love those exploded-view diagrams  in which a machine or object is taken apart into its smallest pieces?

Let's do that to a string!

The challenge

Write a program or function that

inputs a string containing only printable ASCII characters;

dissects the string into groups of non-space equal characters (the "pieces" of the string);

outputs those groups in any convenient format, with some separator between groups.

For example, given the string

```<code>Ah, abracadabra!
</code>```

the output would be the following groups:

```
!
,
A
aaaaa
bb
c
d
h
rr
```

Each group in the output contains equal characters, with spaces removed. A newline has been used as separator between groups. More about allowed formats below.

Rules

The input should be a string or an array of chars. It will only contain printable ASCII chars (the inclusive range from space to tilde). If your language does not support that, you can take the input in the form of numbers representing ASCII codes.

You can assume that the input contains at least one non-space character.

The output should consist of characters (even if the input is by means of ASCII codes). There has to be an unambiguous separator between groups, different than any non-space character that may appear in the input.

If the output is via function return, it may also be an array or strings, or an array of arrays of chars, or similar structure. In that case the structure provides the necessary separation.

A separator between characters of each group is optional. If there is one, the same rule applies: it can't be a non-space character that may appear in the input. Also, it can't be the same separator as used between groups.

Other than that, the format is flexible. Here are some examples:

The groups may be strings separated by newlines, as shown above.

The groups may be separated by any non-ASCII character, such as  ¬. The output for the above input would be the string:

```<code>!¬,¬A¬aaaaa¬bb¬c¬d¬h¬rr
</code>```

The groups may be separated by n>1 spaces (even if n is variable), with chars between each group separated by a single space:

```<code>!  ,    A   a a a a a    b b  c       d   h  r r
</code>```

The output may also be an array or list of strings returned by a function:

```<code>['!', 'A', 'aaaaa', 'bb', 'c', 'd', 'h', 'rr']
</code>```

Or an array of char arrays:

```<code>[['!'], ['A'], ['a', 'a', 'a', 'a', 'a'], ['b', 'b'], ['c'], ['d'], ['h'], ['r', 'r']]
</code>```

Examples of formats that are not allowed, according to the rules:

A comma can't be used as separator (!,,,A,a,a,a,a,a,b,b,c,d,h,r,r), because the input may contain commas.

It's not accepted to drop the separator between groups (!,Aaaaaabbcdhrr) or to use the same separator between groups and within groups (! , A a a a a a b b c d h r r).

The groups may appear in any order in the output. For example: alphabetical order (as in the examples above), order of first appearance in the string, ... The order need not be consistent or even deterministic.

Note that the input cannot contain newline characters, and A and a are different characters (grouping is case-sentitive).

Shortest code in bytes wins.

Test cases

In each test case, first line is input, and the remaining lines are the output, with each group in a different line.

Test case 1:

```
Ah, abracadabra!
!
,
A
aaaaa
bb
c
d
h
rr
```

Test case 2:

```
\o/\o/\o/
///
\\\
ooo
```

Test case 3:

```
A man, a plan, a canal: Panama!
!
,,
:
A
P
aaaaaaaaa
c
ll
mm
nnnn
p
```

Test case 4:

```
"Show me how you do that trick, the one that makes me scream" she said
""
,
S
aaaaa
cc
dd
eeeeeee
hhhhhh
ii
kk
mmmm
n
ooooo
rr
ssss
tttttt
u
ww
y
```

Body:
Emacs, 36 keystrokes

C-SPACE C-EM-xsort-rTABRETURN.RETURN.RETURNC-AC-M-S-%\(\(.\)\2*\)RETURN\1C-QC-JRETURN!

Result

A man, a plan, a canal: Panama! -->

!
,,
:
A
P
aaaaaaaaa
c
ll
mm
nnnn
p

Explanation

C-SPACE C-E

M-x sort-rTAB RETURN .RETURN .RETURN

C-A

C-M-S-% \(\(.\)\2*\)RETURN\1 C-Q C-JRETURN !

Select the input line;

Call sort-regexp-fields with arguments . and .;

Argument #1: Regexp scpecifying records to sort

Argument #2: Regexp scpecifying key within records

Return at line start;

Apply regexp substitution \(\(.\)\2*\) -> \1\n on all matches.


问:
Numbers of purity
Today we'll look at a sequence \$a\$, related to the Collatz function \$f\$:

$$f = \begin{cases}
n/2  & \text{if } n \equiv 0 \text{ (mod }2) \\
3n+1 & \text{if } n \equiv 1 \text{ (mod }2) \\
\end{cases}$$

We call a sequence of the form \$z, f(z), f(f(z)), …\$ a Collatz sequence.

The first number in our sequence, \$a(1)\$, is \$0\$. Under repeated application of \$f\$, it falls into a cycle \$0\to0\to0\to\:\cdots\$

The smallest number we haven't seen yet is 1, making \$a(2)=1\$. Under repeated application of \$f\$, it falls into a cycle \$1\to4\to2\to1\to\cdots\$

Now we have seen the number \$2\$ in the cycle above, so the next smallest number is \$a(3) = 3\$, falling into the cycle \$3\to10\to5\to16\to8\to4\to2\to1\to4\to\cdots\$

In all above cycles we've seen \$4\$ and \$5\$ already, so the next number is \$a(4) = 6\$.

By now you should get the idea. \$a(n)\$ is the smallest number that was not part of any Collatz sequences for all \$a(1), ..., a(n-1)\$

Write a program or function that, given an positive integer \$n\$, returns \$a(n)\$. Shortest code in bytes wins.

Testcases:

```<code>1  -> 0
2  -> 1
3  -> 3
4  -> 6
5  -> 7
6  -> 9
7  -> 12
8  -> 15
9  -> 18
10 -> 19
50 -> 114
</code>```

(This is OEIS sequence A061641.)

答:
Perl6, 96

```<code>my @s;my $a=0;map {while ($a=@s[$a]=$a%2??3*$a+1!!$a/2)>1 {};while @s[++$a] {}},2..slurp;$a.say;
</code>```

Based on the Perl 5 answer. A bit longer since Perl6 syntax is less forgiving than Perl5 syntax, but I'll settle with this for now.

Title: Numbers of purity

Body:
Perl6, 96

my @s;my $a=0;map {while ($a=@s[$a]=$a%2??3*$a+1!!$a/2)>1 {};while @s[++$a] {}},2..slurp;$a.say;

Based on the Perl 5 answer. A bit longer since Perl6 syntax is less forgiving than Perl5 syntax, but I'll settle with this for now.


答:
R, <s>117</s> <s>113</s> <s>109</s> 101 bytes

```<code>D=charToRaw;P=paste;S=strtoi;a=P(i<-scan()+1);while(!all(D(a)==rev(D(a))&&S(a)%%i==0)){a=P(S(a)+1)};a
</code>```

Ungolfed

```<code>i<-scan()        #Takes the input

D=charToRaw      #Some aliases
P=paste
S=strtoi
a=P(i+1)         #Initializes the output

while(!(all(D(a)==rev(D(a)))&&(S(a)%%i==0))) #While the output isn't a palindrom and isn't
                                             #divisible by the output...
    a=P(S(a)+1)

a
</code>```

all(charToRaw(a)==rev(charToRaw(a))) checks if at each position of a the value of a and its reverse are the same (i.e., if a is palindromic).

It might be possible to golf out some bytes by messing around with the types.

Title: Smallest palindrome divisible by the input

Body:
Given a positive integer N, output the smallest positive integer such that this number is a palindrome (i.e. is its own reverse) and is divisible by N.

The palindrome (i.e. the output) must not need a leading zero to be a palindrome, e.g. 080 is not the valid answer for 16.

The input will never be a multiple of 10, because of the previous reason.

Your program may take as much time as necessary, even if in practice it would be way too long to output the answer.

Inputs and outputs

You may take the input through STDIN, as a function argument, or anything similar.

You may print the output to STDOUT, return it from a function, or anything similar.

Inputs and outputs must be in the decimal base.

Test cases

```<code>N        Output
1        1
2        2
16       272
17       272
42       252
111      111
302      87278
1234     28382
</code>```

Scoring

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

Body:
R, <s>117</s> <s>113</s> <s>109</s> 101 bytes

D=charToRaw;P=paste;S=strtoi;a=P(i<-scan()+1);while(!all(D(a)==rev(D(a))&&S(a)%%i==0)){a=P(S(a)+1)};a

Ungolfed

i<-scan()        #Takes the input

D=charToRaw      #Some aliases
P=paste
S=strtoi
a=P(i+1)         #Initializes the output

while(!(all(D(a)==rev(D(a)))&&(S(a)%%i==0))) #While the output isn't a palindrom and isn't
                                             #divisible by the output...
    a=P(S(a)+1)

a

all(charToRaw(a)==rev(charToRaw(a))) checks if at each position of a the value of a and its reverse are the same (i.e., if a is palindromic).

It might be possible to golf out some bytes by messing around with the types.


答:
MATL, 8 bytes

Credit to @alephalpha for his approach, which helped me save 3 bytes

```<code>Zqti+Zp)
</code>```

Try it online!

```<code>Zq    % Take input implicitly. Vector of primes up to that. Call this vector A
ti+   % Duplicate, take second input, add element-wise. Call this vector B
Zp    % Vector containing true for prime numbers in B
)     % Use as an index into A. Display implicitly
</code>```

Title: Variable Prime "Twins"

Body:
MATL, 8 bytes

Credit to @alephalpha for his approach, which helped me save 3 bytes

Zqti+Zp)

Try it online!

Zq    % Take input implicitly. Vector of primes up to that. Call this vector A
ti+   % Duplicate, take second input, add element-wise. Call this vector B
Zp    % Vector containing true for prime numbers in B
)     % Use as an index into A. Display implicitly


答:
Perl6, <s>48</s> <s>47</s> 45

```<code>slurp.comb.Bag.kv.map:{$^a.trim&&say $a x$^b}
</code>```

Thanks to manatwork for the improvements.

Title: Exploded view of a string

Body:
Perl6, <s>48</s> <s>47</s> 45

slurp.comb.Bag.kv.map:{$^a.trim&&say $a x$^b}

Thanks to manatwork for the improvements.


答:
R, 98 bytes

```<code>function(k,u){v=c();for(i in 1:u)if(sum(i%%(1:i)==0)==2&&sum((i+k)%%(1:(i+k))==0)==2){v=c(v,i)};v}
</code>```

Ungolfed :

```<code>function(k,u)
v=c()                                                    #Empty vector

for(i in 1:u)
    if(sum(i%%(1:i)==0)==2&&sum((i+k)%%(1:(i+k))==0)==2) #If both i and i+k only have
                                                         #2 divisors such as the rest of the
                                                         #euclidian division is 0
                                                         #(i.e., they're both prime) :
        v=c(v,i)
v
</code>```

Title: Variable Prime "Twins"

Body:
R, 98 bytes

function(k,u){v=c();for(i in 1:u)if(sum(i%%(1:i)==0)==2&&sum((i+k)%%(1:(i+k))==0)==2){v=c(v,i)};v}

Ungolfed :

function(k,u)
v=c()                                                    #Empty vector

for(i in 1:u)
    if(sum(i%%(1:i)==0)==2&&sum((i+k)%%(1:(i+k))==0)==2) #If both i and i+k only have
                                                         #2 divisors such as the rest of the
                                                         #euclidian division is 0
                                                         #(i.e., they're both prime) :
        v=c(v,i)
v


答:
Haskell, <s>64 63</s> 56 bytes

```<code>x!n|mod x n==0,s<-show x,reverse s==s=x|y<-x+1=y!n
(1!)
</code>```

Call with (1!)16 or simply 1!16. Try it on Ideone.

Body:
Haskell, <s>64 63</s> 56 bytes

x!n|mod x n==0,s<-show x,reverse s==s=x|y<-x+1=y!n
(1!)

Call with (1!)16 or simply 1!16. Try it on Ideone.


问:
Together Everyone Achieves More
(related: one, two, three)

An acrostic is a style of poem/writing where the beginning character of each line, when read vertically, also produces a word or message. For example,

```<code>Together
Everyone
Achieves
More
</code>```

also spells out the word TEAM when the first column is read vertically.

Acrostics are a subset of mesostics, where the vertical word can be anywhere in the horizontal words. For example, the TEAM one above could also be written as a mesostic as follows

```<code>   togeTher
everyonE
       Achieves
       More
</code>```

along with several other variations.

The challenge here will be to produce an acrostic or mesostic from a given list of input words.

Input

A list of words in any any suitable format.

The list will only contain words made from lowercase [a-z].

The list is guaranteed to form an acrostic or a mesostic (no need to handle bogus input).

One of the words in the input will form the vertical word, while the rest make the horizontal words - part of the challenge here is to find the appropriate vertical word, so it cannot be taken separately.

Output

The ASCII-art acrostic or mesostic formed from the input words, written to STDOUT or returned, in any reasonable format.

The corresponding vertical word must be capitalized (as in the examples).

Leading spaces to get the vertical word to line up appropriately are required. Trailing spaces, and leading/trailing newlines are optional. Extra leading spaces are fine as well, so long as the words align correctly.

If both an acrostic and mesostic are possible, output only the acrostic.

If more than one acrostic/mesostic is possible, your code can output any or all of them.

Rules

Either a full program or a function are acceptable.

Standard loopholes are forbidden.

This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples

```<code>['together', 'team', 'everyone', 'achieves', 'more']
Together
Everyone
Achieves
More

['aaa', 'aaa', 'aaa', 'aaa']
Aaa
Aaa
Aaa
# One output, or multiple (of the same) output is allowed

['aaa', 'aaa', 'aab', 'baa']
Aaa
Aaa
Baa
# This is the only allowed output, since others would be mesostic, which are lower priority

['live', 'every', 'love', 'very', 'ohio']
Live
Ohio
Very
Every
# Note that 'live' couldn't be the vertical word since then it would be a mesostic, which is lower priority output

['cow', 'of', 'fox']
cOw
 Fox
# A shorter mesostic test case

['late', 'ballroom', 'anvil', 'to', 'head']
anviL
   bAllroom
    To
   hEad
</code>```

答:
JavaScript (ES6), 255 <s>263 269 286</s>

Edit 17 bytes saved as arbitrary number of leading spaces is allowed

Edit2 some shuffling, 6 byte saved

Edit3 return a list of string instead of a single string with newlines (OP comment to feersum's answer), 8 more bytes saved

For each word in the input list, I use a recursive DFS to find all possibile mesostics/acrostics. Each one is stored as an array with word and target letter position inside the word. Every result found is saved in global result array at position 1 (if it's an acrostic) or 0 if it's a mesostic.

After the complete scan for all words, I get the result at last position in array and build and return its ascii art rapresentation.

l=>(l.map((w,i)=>(r=(p,v,i,a)=>(l[i]='.',w[p]?l.map((v,i)=>~(j=v.search(w[p]))&&r(p+1,v,i,a|j,m[p]=[j,v])):l[p+1]?0:s[+!a]=[...m],l[i]=v))(0,w,i,m=[]),s=[]),m=s.pop(),m.map(([j,v])=>' '.repeat((l+0).length-j)+v.slice(0,j)+v[j].toUpperCase()+v.slice(j+1)))
```
<p><em>Less golfed</em></p>
<pre class="lang-js prettyprint-override"><code>f=l=>(
  l.map((w,i)=>
    // r: recursive DFS function
    // defined here as it uses local w variable
    (r = (p,v,i,a) => (
     l[i] = '.'
     , w[p]
     ? l.map(
       (v,i) => ~(j=v.search(w[p])) &&
                r(p+1, v, i, a|j, m[p] = [j,v])

     )
     : l[p+1] ? 0 // invalid if there are still unused words
              : s[+!a]=[...m] // a is 0 if acrostic
     , l[i] = v)
    )(0, w, i, m=[])
  , s=[]),
  m = s.pop(), // get last result
  // m.map(([j]) => o = o<j ? j : o, o=0), // find offset for alignment
  // no need to find the optimal offset as leading blanks are allowed
  m.map(([j,v]) => ' '.repeat((l+0).length-j)
                   + v.slice(0,j)
                   + v[j].toUpperCase()
                   + v.slice(j+1)
  )
)
</code>```

Test

f=l=>(l.map((w,i)=>(r=(p,v,i,a)=>(l[i]='.',w[p]?l.map((v,i)=>~(j=v.search(w[p]))&&r(p+1,v,i,a|j,m[p]=[j,v])):l[p+1]?0:s[+!a]=[...m],l[i]=v))(0,w,i,m=[]),s=[]),m=s.pop(),m.map(([j,v])=>' '.repeat((l+0).length-j)+v.slice(0,j)+v[j].toUpperCase()+v.slice(j+1)))

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

;[
 ['together', 'team', 'everyone', 'achieves', 'more']
,['aaa', 'aaa', 'aaa', 'aaa']
,['aaa', 'aaa', 'aab', 'baa']
,['live', 'every', 'love', 'very', 'ohio']
,['cow', 'of', 'fox']
,['late', 'ballroom', 'anvil', 'to', 'head']
].forEach(l=>console.log(f(l).join`\n`))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id=O>``````

Title: Together Everyone Achieves More

Body:
JavaScript (ES6), 255 <s>263 269 286</s>

Edit 17 bytes saved as arbitrary number of leading spaces is allowed

Edit2 some shuffling, 6 byte saved

Edit3 return a list of string instead of a single string with newlines (OP comment to feersum's answer), 8 more bytes saved

For each word in the input list, I use a recursive DFS to find all possibile mesostics/acrostics. Each one is stored as an array with word and target letter position inside the word. Every result found is saved in global result array at position 1 (if it's an acrostic) or 0 if it's a mesostic.

After the complete scan for all words, I get the result at last position in array and build and return its ascii art rapresentation.

l=>(l.map((w,i)=>(r=(p,v,i,a)=>(l[i]='.',w[p]?l.map((v,i)=>~(j=v.search(w[p]))&&r(p+1,v,i,a|j,m[p]=[j,v])):l[p+1]?0:s[+!a]=[...m],l[i]=v))(0,w,i,m=[]),s=[]),m=s.pop(),m.map(([j,v])=>' '.repeat((l+0).length-j)+v.slice(0,j)+v[j].toUpperCase()+v.slice(j+1)))

Less golfed

f=l=>(
  l.map((w,i)=>
    // r: recursive DFS function
    // defined here as it uses local w variable
    (r = (p,v,i,a) => (
     l[i] = '.'
     , w[p]
     ? l.map(
       (v,i) => ~(j=v.search(w[p])) &&
                r(p+1, v, i, a|j, m[p] = [j,v])

     )
     : l[p+1] ? 0 // invalid if there are still unused words
              : s[+!a]=[...m] // a is 0 if acrostic
     , l[i] = v)
    )(0, w, i, m=[])
  , s=[]),
  m = s.pop(), // get last result
  // m.map(([j]) => o = o<j ? j : o, o=0), // find offset for alignment
  // no need to find the optimal offset as leading blanks are allowed
  m.map(([j,v]) => ' '.repeat((l+0).length-j)
                   + v.slice(0,j)
                   + v[j].toUpperCase()
                   + v.slice(j+1)
  )
)

Test

f=l=>(l.map((w,i)=>(r=(p,v,i,a)=>(l[i]='.',w[p]?l.map((v,i)=>~(j=v.search(w[p]))&&r(p+1,v,i,a|j,m[p]=[j,v])):l[p+1]?0:s[+!a]=[...m],l[i]=v))(0,w,i,m=[]),s=[]),m=s.pop(),m.map(([j,v])=>' '.repeat((l+0).length-j)+v.slice(0,j)+v[j].toUpperCase()+v.slice(j+1)))

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

;[
 ['together', 'team', 'everyone', 'achieves', 'more']
,['aaa', 'aaa', 'aaa', 'aaa']
,['aaa', 'aaa', 'aab', 'baa']
,['live', 'every', 'love', 'very', 'ohio']
,['cow', 'of', 'fox']
,['late', 'ballroom', 'anvil', 'to', 'head']
].forEach(l=>console.log(f(l).join`\n`))

<pre id=O></pre>


问:
What base is this number in?
Here's a nice easy challenge:

Given a string that represents a number in an unknown base, determine the lowest possible base that number might be in. The string will only contain 0-9, a-z. If you like, you may choose to take uppercase letters instead of lowercase, but please specify this. You must output this lowest possible base in decimal.

Here is a more concrete example. If the input string was "01234", it is impossible for this number to be in binary, since 2, 3, and 4 are all undefined in binary. Similarly, this number cannot be in base 3, or base 4. Therefore, this number must be in base-5, or a higher base, so you should output '5'.

Your code must work for any base between base 1 (unary, all '0's) and base 36 ('0-9' and 'a-z').

You may take input and provide output in any reasonable format. Base-conversion builtins are allowed. As usual, standard loopholes apply, and the shortest answer in bytes is the winner!

Test IO:

```<code>#Input          #Output
00000       --> 1
123456      --> 7
ff          --> 16
4815162342  --> 9
42          --> 5
codegolf    --> 25
0123456789abcdefghijklmnopqrstuvwxyz    --> 36
</code>```

答:
Scala, 25 bytes

print((args(0).max-8)%39)

Run it like:

$ scala whatbase.scala 0123456789abcdefghijklmnopqrstuvwxyz

Title: What base is this number in?


问:
Russian Roulette
Write a program which plays Russian Roulette!

If the program is started,

there should be a 5 in 6 chance of it ending normally after printing "I survived!"

there should be a 1 in 6 chance of the program crashing. (segmentation fault, etc.)

No input, and no other outputs are allowed.

The randomness must be fair: it must have a uniform probability distribution. This means an uninitialized variable (or a RNG without seed) MOD 6 will not be sufficient.

If the solution works with only one dedicated operating system / platform, you will receive a 6 byte penalty to the score.

Shortest code wins, not sooner than 10 days after first valid answer.

答:
Java, 149

```<code>public class R{public static void main(String[]s){int[]a={1,1,1,1,1};System.out.println(a[new java.util.Random().nextInt(7)]>0?"I survived!":"");}}
</code>```

Fails with an "Array out of bounds" error. Managed to shave a few characters by using anonymous Random object (no imports).

Title: Russian Roulette

Body:
Java, 149

public class R{public static void main(String[]s){int[]a={1,1,1,1,1};System.out.println(a[new java.util.Random().nextInt(7)]>0?"I survived!":"");}}

Fails with an "Array out of bounds" error. Managed to shave a few characters by using anonymous Random object (no imports).


Body:
Haskell, <s>45</s> <s>37</s> 34 bytes

(+)>>=until((reverse>>=(==)).show)


答:
CJam, 17 bytes

Either as a full program:

```<code>q~{_mp\W$+mp&},p;
</code>```

Try it online!

Or as an unnamed block:

```<code>{:X;{_mp\X+mp&},}
</code>```

Try it online!

Title: Variable Prime "Twins"

Body:
CJam, 17 bytes

Either as a full program:

q~{_mp\W$+mp&},p;

Try it online!

Or as an unnamed block:

{:X;{_mp\X+mp&},}

Try it online!


问:
How can I get a repdigit?
In honor of how much rep I had several hours ago, when I first thought of this challenge:

Numbers like this that are made up of a single digit repeating are called repdigits. Repdigits are fun! Every body would be more happy if the amount of rep they had was a repdigit¹, but I am impatient, so you need to help me find out the fastest way to get to a repdigit.

Here is your challenge:

Given a positive integers representing reputation, output the minimum amount of rep they need to gain to get to a repdigit. For example, at the time of writing this challenge, user Martin Ender had 102,856 rep. The nearest rep-digit is 111,111, so he would need to gain: 8255 rep to be at a repdigit.

Since people dislike losing rep, we will only consider non-negative changes. This means that, for example, if someone is at 12 rep, rather than losing 1 rep, the solution is to gain 10 rep. This allows '0' to be a valid output, since anyone who has 111 rep is already at a repdigit.

Input and output can be in any reasonable format, and since it is impossible to have less than 1 rep on any Stack Exchange site, you can assume no inputs will be less than 1.

One cornercase to note:

If a user has less than 10 rep, they are already at a repdigit, and so they also need '0'.

Test IO:

```<code>#Input      #Ouput
8           0
100         11
113         109
87654321    1234567
42          2
20000       2222
11132       11090
</code>```

Standard loopholes apply, and the shortest solution in bytes wins!

答:
C#, 82 bytes

```<code>using System.Linq;n=>{int i=n;while((i+"").Distinct().Count()!=1)++i;return i-n;};
</code>```

Title: How can I get a repdigit?

Body:
C#, 82 bytes

using System.Linq;n=>{int i=n;while((i+"").Distinct().Count()!=1)++i;return i-n;};


问:
Highlight the Bounding Box, Part I: Cartesian Grid
You're given a rectangular grid of the characters . and #, like this:

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

Your task is to fill the entire axis-aligned bounding box of the # with further #:

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

The axis-aligned bounding box is the smallest rectangle which contains all the #.

Want more? Try Part II!

Rules

You may use any two distinct printable ASCII characters (0x20 to 0x7E, inclusive), in place of # and .. I'll continue referring to them as # and . for the remainder of the specification though.

Input and output may either be a single linefeed-separated string or a list of strings (one for each line), but the format has to be consistent.

You may assume that the input contains at least one # and all lines are the same length.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

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

Test Cases

Each test case has input and output next to each other.

```<code>#    #

...    ...
#..    #..
...    ...

...    ...
#..    ###
..#    ###

.#.    ###
#..    ###
..#    ###

.....    .....
.#.#.    .###.
.....    .....

...    ...
.#.    .#.
...    .#.
.#.    .#.
...    ...

..........    ..........
..........    ..........
....#.....    ....#.....
..........    ..........

..........    ..........
..........    ..........
....#.....    ...##.....
...#......    ...##.....

..........    ..........
..#.......    ..###.....
....#.....    ..###.....
...#......    ..###.....

..........    ..........
..#.......    ..######..
....#..#..    ..######..
...#......    ..######..

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

答:
Mathematica, <s>91</s> 70 bytes

21 bytes saved due to @MartinEnder.

```<code>ReplacePart["."+0#,Tuples[Range@@@MinMax/@(#~Position~"#")]]->"#"]&
</code>```

Anonymous function. Takes a character matrix as input an returns a character matrix as output. The Unicode character is U+F3C7 for \[Transpose].

Body:
Mathematica, <s>91</s> 70 bytes

21 bytes saved due to @MartinEnder.

ReplacePart["."+0#,Tuples[Range@@@MinMax/@(#~Position~"#")]]->"#"]&

Anonymous function. Takes a character matrix as input an returns a character matrix as output. The Unicode character is U+F3C7 for \[Transpose].


答:
Perl (26 22)

```<code>$_=3x pop;say s|333||g
</code>```

This version (ab)uses Perl's regex engine. It reads a number as the last command line argument (pop) and builds a string of 3s of this length ("3" x $number). The regex substitution operator (s///, here written with different delimitiers because of the puzzle's rules and with a global flag) substitues three characters by the empty string and returns the number of substitutions, which is the input number integer-divided by three. It could even be written without 3, but the above version looks funnier.

```<code>$ perl -E '$_=3x pop;say s|333||g' 42
14
</code>```

Title: Divide a number by 3 without using *, /, +, -, % operators

Body:
Quoting this question on SO (Spoiler alert!):

This question has been asked in an Oracle interview.

How would you divide a number by 3 without using *, /, +, -, %,
  operators?

The number may be signed or unsigned.

The task is solvable, but see if you can write the shortest code.

Rules:

Perform the required integer division (/3)

Do not use the non-text-based operators *, /, +, -, or % (or their equivalents, such as __div__ or add()). This also applies to incrementing and decrementing operators, like i++ or i--. Use of operators for string concatenation and formatting are OK. Using these characters for different operators, such as unary - operator for negative numbers, or * to represent a pointer in C is OK as well.

Input value can be arbitrarily large (whatever your system can handle), both positive and negative

Input can be on STDIN or ARGV or entered any other way

Create the shortest code you can to do the above

Body:
Perl (26 22)

$_=3x pop;say s|333||g

This version (ab)uses Perl's regex engine. It reads a number as the last command line argument (pop) and builds a string of 3s of this length ("3" x $number). The regex substitution operator (s///, here written with different delimitiers because of the puzzle's rules and with a global flag) substitues three characters by the empty string and returns the number of substitutions, which is the input number integer-divided by three. It could even be written without 3, but the above version looks funnier.

$ perl -E '$_=3x pop;say s|333||g' 42
14


问:
Creating a Crossed Square

Creating a Crossed Square

You are to take input of an integer of one or more and output a square made of any printable character of your choice with a diagonal cross through the centre.

The general idea is for the output to be a hollow square that has a diagonal cross through it.:

```<code>Input: 7
Output:
*******
*#   #*
* # # *
*  #  *
* # # *
*#   #*
*******
</code>```

In the above example the '*'s represent the outer box and the '#'s represent the diagonal cross.

Note that the above example uses two different characters so that it is easier to see what the output looks like, your program should use one character only.

Input

An integer of 1 or more, it is guaranteed to be odd.

Output

A square that is made up of a character of your choice with a cross through the middle.

The cross must be diagonal

The square may be output via the function or written to output

Trailing newlines are okay

Can output as a graphic, diagram or image if you wish too

Examples

```<code>Input: 1
Output:
*

Input: 3
Output:
***
***
***

Input: 5
Output:
*****
** **
* * *
** **
*****

Input: 7
Output:
*******
**   **
* * * *
*  *  *
* * * *
**   **
*******
</code>```

Specs

Functions or full programs are allowed

You can get input by your preferred means

Standard loopholes are disallowed

Programs must work without any additional statements i.e. usings in C#, they must be included in the entry

You can output from a function or print the result

This is code golf so the shortest solution wins.

答:
C, <s>140</s> <s>121</s> 114 bytes

19 bytes thanks to Quentin.

7 bytes saved by switching from a double-nested loop to one loop.

main(a){scanf("%d",&a);for(int i=0;i<a*a;i++,i%a||puts(""))putchar(i/a&&i/a^a-1&&i%a&&-~i%a&&i%-~a&&i%~-a?32:42);}
```

Golfing suggestions welcome.

Title: Creating a Crossed Square

Body:
C, <s>140</s> <s>121</s> 114 bytes

19 bytes thanks to Quentin.

7 bytes saved by switching from a double-nested loop to one loop.

main(a){scanf("%d",&a);for(int i=0;i<a*a;i++,i%a||puts(""))putchar(i/a&&i/a^a-1&&i%a&&-~i%a&&i%-~a&&i%~-a?32:42);}

Golfing suggestions welcome.


答:
MATL, <s>20</s> <s>19</s> 17 bytes

```<code>2-:XdtP!+~TTYa1YG
</code>```

You can try it experimentally in MATL online. You may need to refresh the page if it doesn't work.

Sample run:

ASCII version: 19 bytes

```<code>2-:XdtP!+~TTYa~42*c
</code>```

Try it online!

Title: Creating a Crossed Square

Body:
Creating a Crossed Square

You are to take input of an integer of one or more and output a square made of any printable character of your choice with a diagonal cross through the centre.

The general idea is for the output to be a hollow square that has a diagonal cross through it.:

```<code>Input: 7
Output:
*******
*#   #*
* # # *
*  #  *
* # # *
*#   #*
*******
</code>```

In the above example the '*'s represent the outer box and the '#'s represent the diagonal cross.

Note that the above example uses two different characters so that it is easier to see what the output looks like, your program should use one character only.

Input

An integer of 1 or more, it is guaranteed to be odd.

Output

A square that is made up of a character of your choice with a cross through the middle.

The cross must be diagonal

The square may be output via the function or written to output

Trailing newlines are okay

Can output as a graphic, diagram or image if you wish too

Examples

```<code>Input: 1
Output:
*

Input: 3
Output:
***
***
***

Input: 5
Output:
*****
** **
* * *
** **
*****

Input: 7
Output:
*******
**   **
* * * *
*  *  *
* * * *
**   **
*******
</code>```

Specs

Functions or full programs are allowed

You can get input by your preferred means

Standard loopholes are disallowed

Programs must work without any additional statements i.e. usings in C#, they must be included in the entry

You can output from a function or print the result

This is code golf so the shortest solution wins.

Body:
MATL, <s>20</s> <s>19</s> 17 bytes

2-:XdtP!+~TTYa1YG

You can try it experimentally in MATL online. You may need to refresh the page if it doesn't work.

Sample run:

ASCII version: 19 bytes

2-:XdtP!+~TTYa~42*c

Try it online!


答:
Java 7, <s>131</s> <s>130</s> <s>128</s> <s>125</s> <s>124</s> 122 bytes

```<code>String c(int n){String r="";for(int i=n,j;n-->0;r+="\n")for(j=0;j<n;r+=i*j<1|n-i<2|n-j<2|i==j|i==n-++j?"*":" ");return r;}
</code>```

3 bytes saved thanks to @LeakyNun;

1 byte saved thanks to @OliverGrégoire in my answer for the Draw a hollow square of # with given width challenge;

2 bytes saved thanks to @cliffroot.

Ungolfed & test code:

Try it here.

```<code>class M{
  static String c(int n){
    String r = "";
    for(int i = n, j; n-- > 0; r += "\n"){
      for(j = 0; j < n;
            r += i < 1      // Responsible for the first horizontal line
               | j < 1      // Responsible for the first vertical line
               | n-i < 2    // Responsible for the last horizontal line
               | n-j < 2    // Responsible for the last vertical line
               | i == j     // Responsible for the top-left to bottom-right diagonal line
               | i == n-++j // Responsible for the top-right to bottom-left diagonal line (and increasing j)
             ? "*"
             : " ");
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c(1));
    System.out.println(c(3));
    System.out.println(c(5));
    System.out.println(c(7));
  }
}
</code>```

Output:

```<code>*

***
***
***

*****
** **
* * *
** **
*****

*******
**   **
* * * *
*  *  *
* * * *
**   **
*******
</code>```

Title: Creating a Crossed Square

Body:
Java 7, <s>131</s> <s>130</s> <s>128</s> <s>125</s> <s>124</s> 122 bytes

String c(int n){String r="";for(int i=n,j;n-->0;r+="\n")for(j=0;j<n;r+=i*j<1|n-i<2|n-j<2|i==j|i==n-++j?"*":" ");return r;}

3 bytes saved thanks to @LeakyNun;

1 byte saved thanks to @OliverGrégoire in my answer for the Draw a hollow square of # with given width challenge;

2 bytes saved thanks to @cliffroot.

Ungolfed & test code:

Try it here.

class M{
  static String c(int n){
    String r = "";
    for(int i = n, j; n-- > 0; r += "\n"){
      for(j = 0; j < n;
            r += i < 1      // Responsible for the first horizontal line
               | j < 1      // Responsible for the first vertical line
               | n-i < 2    // Responsible for the last horizontal line
               | n-j < 2    // Responsible for the last vertical line
               | i == j     // Responsible for the top-left to bottom-right diagonal line
               | i == n-++j // Responsible for the top-right to bottom-left diagonal line (and increasing j)
             ? "*"
             : " ");
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c(1));
    System.out.println(c(3));
    System.out.println(c(5));
    System.out.println(c(7));
  }
}

Output:

*

***
***
***

*****
** **
* * *
** **
*****

*******
**   **
* * * *
*  *  *
* * * *
**   **
*******


答:
Matlab, <s>68 66 64</s> 58 bytes

Since graphical output is allowed too:

```<code>k=input('');[x,y]=ndgrid(abs(-k:k));spy(~(max(x,y)<k&x-y))
</code>```

Which outputs e.g.

The ascii only versions would be:

This is using the indexing 0,1,2,3,...

```<code>k=input('');[x,y]=ndgrid(abs(-k:k));[(max(x,y)==k|~(x-y))*42,'']
</code>```

Alternatively with the indexing 1,3,7,...:

```<code>n=input('');k=1:n;m=eye(n);m([k,end-k+1])=1;[(m|flip(m'))*42,'']
</code>```

Title: Creating a Crossed Square

Body:
Matlab, <s>68 66 64</s> 58 bytes

Since graphical output is allowed too:

k=input('');[x,y]=ndgrid(abs(-k:k));spy(~(max(x,y)<k&x-y))

Which outputs e.g.

The ascii only versions would be:

This is using the indexing 0,1,2,3,...

k=input('');[x,y]=ndgrid(abs(-k:k));[(max(x,y)==k|~(x-y))*42,'']

Alternatively with the indexing 1,3,7,...:

n=input('');k=1:n;m=eye(n);m([k,end-k+1])=1;[(m|flip(m'))*42,'']


答:
R, 102 bytes

```<code>    n=scan();for(i in 1:n){for(j in 1:n){z=" ";if(i%in%c(1,n,n-j+1)|j%in%c(1,i,n))z="*";cat(z)};cat("\n")}
</code>```

Note that it is more efficient to express the condition using %in% than i==1|j==1|...

Title: Creating a Crossed Square

Body:
R, 102 bytes

    n=scan();for(i in 1:n){for(j in 1:n){z=" ";if(i%in%c(1,n,n-j+1)|j%in%c(1,i,n))z="*";cat(z)};cat("\n")}

Note that it is more efficient to express the condition using %in% than i==1|j==1|...


答:
C#, <s>262</s> 251 bytes

```<code>s=>{int l,t,r,b,i,j,k;l=t=r=b=i=-1;for(;++i<s.Length;){j=s[i].IndexOf('#');if(j>-1){k=s[i].LastIndexOf('#');l=l==-1|j<l?j:l;t=t==-1?i:t;r=k>r?k:r;b=i;}}for(i=t;i<=b;++i)for(j=l;j<=r;){var c=s[i].ToCharArray();c[j++]='#';s[i]=new string(c);}return s;};
</code>```

Will golf it further when I have more time.

It compiles into a Func<string[], string[]>.

Formatted version:

```<code>s =>
{
    int l, t, r, b, i, j, k;
    l = t = r = b = i = -1;

    for (; ++i < s.Length;)
    {
        j = s[i].IndexOf('#');
        if (j > -1)
        {
            k = s[i].LastIndexOf('#');

            l = l == -1 | j < l ? j : l;

            t = t == -1 ? i : t;

            r = k > r ? k : r;

            b = i;
        }
    }

    for (i = t; i <= b; ++i)
        for (j = l; j <= r;)
        {
            var c = s[i].ToCharArray();
            c[j++] = '#';
            s[i] = new string(c);
        }

    return s;
};
</code>```

Title: Highlight the Bounding Box, Part I: Cartesian Grid

Body:
You're given a rectangular grid of the characters . and #, like this:

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

Your task is to fill the entire axis-aligned bounding box of the # with further #:

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

The axis-aligned bounding box is the smallest rectangle which contains all the #.

Want more? Try Part II!

Rules

You may use any two distinct printable ASCII characters (0x20 to 0x7E, inclusive), in place of # and .. I'll continue referring to them as # and . for the remainder of the specification though.

Input and output may either be a single linefeed-separated string or a list of strings (one for each line), but the format has to be consistent.

You may assume that the input contains at least one # and all lines are the same length.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

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

Test Cases

Each test case has input and output next to each other.

```<code>#    #

...    ...
#..    #..
...    ...

...    ...
#..    ###
..#    ###

.#.    ###
#..    ###
..#    ###

.....    .....
.#.#.    .###.
.....    .....

...    ...
.#.    .#.
...    .#.
.#.    .#.
...    ...

..........    ..........
..........    ..........
....#.....    ....#.....
..........    ..........

..........    ..........
..........    ..........
....#.....    ...##.....
...#......    ...##.....

..........    ..........
..#.......    ..###.....
....#.....    ..###.....
...#......    ..###.....

..........    ..........
..#.......    ..######..
....#..#..    ..######..
...#......    ..######..

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

Body:
C#, <s>262</s> 251 bytes

s=>{int l,t,r,b,i,j,k;l=t=r=b=i=-1;for(;++i<s.Length;){j=s[i].IndexOf('#');if(j>-1){k=s[i].LastIndexOf('#');l=l==-1|j<l?j:l;t=t==-1?i:t;r=k>r?k:r;b=i;}}for(i=t;i<=b;++i)for(j=l;j<=r;){var c=s[i].ToCharArray();c[j++]='#';s[i]=new string(c);}return s;};

Will golf it further when I have more time.

It compiles into a Func<string[], string[]>.

Formatted version:

s =>
{
    int l, t, r, b, i, j, k;
    l = t = r = b = i = -1;

    for (; ++i < s.Length;)
    {
        j = s[i].IndexOf('#');
        if (j > -1)
        {
            k = s[i].LastIndexOf('#');

            l = l == -1 | j < l ? j : l;

            t = t == -1 ? i : t;

            r = k > r ? k : r;

            b = i;
        }
    }

    for (i = t; i <= b; ++i)
        for (j = l; j <= r;)
        {
            var c = s[i].ToCharArray();
            c[j++] = '#';
            s[i] = new string(c);
        }

    return s;
};


答:
JavaScript (ES6), 96 bytes

f=
n=>[...Array(n--)].map((_,i,a)=>a.map((_,j)=>i&&j&&n-i&&n-j&&i-j&&n-i-j?' ':'*').join``).join`
`
;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type=number min=1 step=2 oninput=  o.textContent=f(this.value)><pre id=o></code>```

Title: Creating a Crossed Square

Body:
JavaScript (ES6), 96 bytes

f=
n=>[...Array(n--)].map((_,i,a)=>a.map((_,j)=>i&&j&&n-i&&n-j&&i-j&&n-i-j?' ':'*').join``).join`
`
;

<input type=number min=1 step=2 oninput=  o.textContent=f(this.value)><pre id=o>


Title: Creating a Crossed Square

Body:
Java, 130 bytes

s->{for(int i=0;i<s;i++)for(int j=0;j<s;j++)System.out.print((s-1-i==j||i==j||i==0||j==0||i==s-1||j==s-1)?j==s-1?"*\n":"*":" ");};

Test Program

Consumer<Integer> consumer = s -> {
        for (int i = 0; i < s; i++) {
            for (int j = 0; j < s; j++) {
                System.out.print((s - 1 - i == j || i == j || i == 0 || j == 0 || i == s - 1 || j == s - 1) ? j == s - 1 ? "*\n" : "*" : " ");
            }
        }
    };

    consumer.accept(20);


答:
T-SQL 56 44 40 + 6

```<code> if 1/cast(ceiling(rand()*6)-1as int)<2print'I Survived!'
</code>```

Credit Sean Cheshire for calling out cast as unnecessary

```<code> if 1/ceiling(rand()*6-1)<2print'I Survived!'
</code>```

Credit personal message from Sean Cheshire for suggestion to change ceiling to floor.

```<code> if 1/floor(rand()*6)<1print'I Survived!'
</code>```

Death Err Msg:
Msg 8134, Level 16, State 1, Line 3
Divide by zero error encountered.

Title: Russian Roulette

Body:
Write a program which plays Russian Roulette!

If the program is started,

there should be a 5 in 6 chance of it ending normally after printing "I survived!"

there should be a 1 in 6 chance of the program crashing. (segmentation fault, etc.)

No input, and no other outputs are allowed.

The randomness must be fair: it must have a uniform probability distribution. This means an uninitialized variable (or a RNG without seed) MOD 6 will not be sufficient.

If the solution works with only one dedicated operating system / platform, you will receive a 6 byte penalty to the score.

Shortest code wins, not sooner than 10 days after first valid answer.

Body:
T-SQL 56 44 40 + 6

 if 1/cast(ceiling(rand()*6)-1as int)<2print'I Survived!'

Credit Sean Cheshire for calling out cast as unnecessary

 if 1/ceiling(rand()*6-1)<2print'I Survived!'

Credit personal message from Sean Cheshire for suggestion to change ceiling to floor.

 if 1/floor(rand()*6)<1print'I Survived!'

Death Err Msg:
Msg 8134, Level 16, State 1, Line 3
Divide by zero error encountered.


答:
Python, <s>114 110 96</s> 90 bytes

Totally changed:

```<code>lambda n:[bin(sum(2**p for p in[range(n),{0,n-1,r,n-1-r}][0<r<n-1]))[2:]for r in range(n)]
</code>```

Returns a list of strings, characters using 1 and 0.

-6 bytes thanks to TheBikingViking

Test it at ideone

Previous Python 2 @110

```<code>def f(n):g=range(n);n-=1;print'\n'.join(''.join((c in(r,n-r,0,n)or r in(0,n))and'#'or' 'for c in g)for r in g)
</code>```

Test it on ideone

Title: Creating a Crossed Square

Body:
Python, <s>114 110 96</s> 90 bytes

Totally changed:

lambda n:[bin(sum(2**p for p in[range(n),{0,n-1,r,n-1-r}][0<r<n-1]))[2:]for r in range(n)]

Returns a list of strings, characters using 1 and 0.

-6 bytes thanks to TheBikingViking

Test it at ideone

Previous Python 2 @110

def f(n):g=range(n);n-=1;print'\n'.join(''.join((c in(r,n-r,0,n)or r in(0,n))and'#'or' 'for c in g)for r in g)

Test it on ideone


答:
C#, 103 80 Bytes

```<code>int f(int p){int x=p;while(x+""!=string.Concat((x+"").Reverse()))x+=p;return x;}
</code>```

Ungolfed

```<code>int f(int p)
{
   int x = p;
   while (x + "" != string.Concat((x + "").Reverse()))
      x += p;
   return x;
}
</code>```

Body:
Given a positive integer N, output the smallest positive integer such that this number is a palindrome (i.e. is its own reverse) and is divisible by N.

The palindrome (i.e. the output) must not need a leading zero to be a palindrome, e.g. 080 is not the valid answer for 16.

The input will never be a multiple of 10, because of the previous reason.

Your program may take as much time as necessary, even if in practice it would be way too long to output the answer.

Inputs and outputs

You may take the input through STDIN, as a function argument, or anything similar.

You may print the output to STDOUT, return it from a function, or anything similar.

Inputs and outputs must be in the decimal base.

Test cases

```<code>N        Output
1        1
2        2
16       272
17       272
42       252
111      111
302      87278
1234     28382
</code>```

Scoring

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

Body:
C#, 103 80 Bytes

int f(int p){int x=p;while(x+""!=string.Concat((x+"").Reverse()))x+=p;return x;}

Ungolfed

int f(int p)
{
   int x = p;
   while (x + "" != string.Concat((x + "").Reverse()))
      x += p;
   return x;
}


答:
PowerShell v2+, 44 bytes

```<code>[char[]]$args[0]-ne32|group|%{-join$_.Group}
</code>```

Takes input $args[0] as a command-line argument literal string. Casts that as a char-array, and uses the -not equal operator to pull out spaces (ASCII 32). This works because casting has a higher order precedence, and when an array is used as the left-hand operator with a scalar as the right-hand, it acts like a filter.

We pass that array of characters to Group-Object, which does exactly what it says. Note that since we're passing characters, not strings, this properly groups with case-sensitivity.

Now, we've got a custom object(s) that has group names, counts, etc. If we just print that we'll have a host of extraneous output. So, we need to pipe those into a loop |%{...} and each iteration -join the .Group together into a single string. Those resultant strings are left on the pipeline, and output is implicit at program completion.

Example

```<code>PS C:\Tools\Scripts\golfing> .\exploded-view-of-substrings.ps1 'Programming Puzzles and Code Golf'
PP
rr
ooo
gg
aa
mm
i
nn
u
zz
ll
ee
s
dd
C
G
f
</code>```

Title: Exploded view of a string

Body:
Don't you love those exploded-view diagrams  in which a machine or object is taken apart into its smallest pieces?

Let's do that to a string!

The challenge

Write a program or function that

inputs a string containing only printable ASCII characters;

dissects the string into groups of non-space equal characters (the "pieces" of the string);

outputs those groups in any convenient format, with some separator between groups.

For example, given the string

```<code>Ah, abracadabra!
</code>```

the output would be the following groups:

```
!
,
A
aaaaa
bb
c
d
h
rr
```

Each group in the output contains equal characters, with spaces removed. A newline has been used as separator between groups. More about allowed formats below.

Rules

The input should be a string or an array of chars. It will only contain printable ASCII chars (the inclusive range from space to tilde). If your language does not support that, you can take the input in the form of numbers representing ASCII codes.

You can assume that the input contains at least one non-space character.

The output should consist of characters (even if the input is by means of ASCII codes). There has to be an unambiguous separator between groups, different than any non-space character that may appear in the input.

If the output is via function return, it may also be an array or strings, or an array of arrays of chars, or similar structure. In that case the structure provides the necessary separation.

A separator between characters of each group is optional. If there is one, the same rule applies: it can't be a non-space character that may appear in the input. Also, it can't be the same separator as used between groups.

Other than that, the format is flexible. Here are some examples:

The groups may be strings separated by newlines, as shown above.

The groups may be separated by any non-ASCII character, such as  ¬. The output for the above input would be the string:

```<code>!¬,¬A¬aaaaa¬bb¬c¬d¬h¬rr
</code>```

The groups may be separated by n>1 spaces (even if n is variable), with chars between each group separated by a single space:

```<code>!  ,    A   a a a a a    b b  c       d   h  r r
</code>```

The output may also be an array or list of strings returned by a function:

```<code>['!', 'A', 'aaaaa', 'bb', 'c', 'd', 'h', 'rr']
</code>```

Or an array of char arrays:

```<code>[['!'], ['A'], ['a', 'a', 'a', 'a', 'a'], ['b', 'b'], ['c'], ['d'], ['h'], ['r', 'r']]
</code>```

Examples of formats that are not allowed, according to the rules:

A comma can't be used as separator (!,,,A,a,a,a,a,a,b,b,c,d,h,r,r), because the input may contain commas.

It's not accepted to drop the separator between groups (!,Aaaaaabbcdhrr) or to use the same separator between groups and within groups (! , A a a a a a b b c d h r r).

The groups may appear in any order in the output. For example: alphabetical order (as in the examples above), order of first appearance in the string, ... The order need not be consistent or even deterministic.

Note that the input cannot contain newline characters, and A and a are different characters (grouping is case-sentitive).

Shortest code in bytes wins.

Test cases

In each test case, first line is input, and the remaining lines are the output, with each group in a different line.

Test case 1:

```
Ah, abracadabra!
!
,
A
aaaaa
bb
c
d
h
rr
```

Test case 2:

```
\o/\o/\o/
///
\\\
ooo
```

Test case 3:

```
A man, a plan, a canal: Panama!
!
,,
:
A
P
aaaaaaaaa
c
ll
mm
nnnn
p
```

Test case 4:

```
"Show me how you do that trick, the one that makes me scream" she said
""
,
S
aaaaa
cc
dd
eeeeeee
hhhhhh
ii
kk
mmmm
n
ooooo
rr
ssss
tttttt
u
ww
y
```

Body:
PowerShell v2+, 44 bytes

[char[]]$args[0]-ne32|group|%{-join$_.Group}

Takes input $args[0] as a command-line argument literal string. Casts that as a char-array, and uses the -not equal operator to pull out spaces (ASCII 32). This works because casting has a higher order precedence, and when an array is used as the left-hand operator with a scalar as the right-hand, it acts like a filter.

We pass that array of characters to Group-Object, which does exactly what it says. Note that since we're passing characters, not strings, this properly groups with case-sensitivity.

Now, we've got a custom object(s) that has group names, counts, etc. If we just print that we'll have a host of extraneous output. So, we need to pipe those into a loop |%{...} and each iteration -join the .Group together into a single string. Those resultant strings are left on the pipeline, and output is implicit at program completion.

Example

PS C:\Tools\Scripts\golfing> .\exploded-view-of-substrings.ps1 'Programming Puzzles and Code Golf'
PP
rr
ooo
gg
aa
mm
i
nn
u
zz
ll
ee
s
dd
C
G
f


答:
VBSCRIPT, 47 bytes

```<code>do:i=i+1:a=n*i:loop until a=eval(strreverse(a))
</code>```

ungolfed

```<code>do                     #starts the loop
i=i+1                  #increments i, we do it first to start at 1 instead of 0
a=                     #a is the output
n*i                    #multiply our input n by i
loop until
a=eval(strreverse(a))  #end the loop when our output is equal to its reverse
</code>```

Body:
VBSCRIPT, 47 bytes

do:i=i+1:a=n*i:loop until a=eval(strreverse(a))

ungolfed

do                     #starts the loop
i=i+1                  #increments i, we do it first to start at 1 instead of 0
a=                     #a is the output
n*i                    #multiply our input n by i
loop until
a=eval(strreverse(a))  #end the loop when our output is equal to its reverse


答:
MATLAB, 76 bytes

```<code>function s=p(n)
f=1;s='01';while(any(s~=fliplr(s))) s=num2str(n*f);f=f+1;end
</code>```

Call format is p(302) result is a string.

Nothing clever here. It does a linear search, using the num2str() and fliplr() functions.

This ugly arrangement is a touch shorter than using a while(1) ... if ... break end pattern.

Ungolfed

```<code>function s = findFirstPalindromeFactor(n)
  f = 1;                        % factor
  s = '01';                     % non-palindromic string for first try
  while( all(s ~= fliplr(s)) )  % test s not palindrome
    s = num2str( n * f );       % factor of input as string
    f = f + 1;                  % next factor
  end

</code>```

Body:
MATLAB, 76 bytes

function s=p(n)
f=1;s='01';while(any(s~=fliplr(s))) s=num2str(n*f);f=f+1;end

Call format is p(302) result is a string.

Nothing clever here. It does a linear search, using the num2str() and fliplr() functions.

This ugly arrangement is a touch shorter than using a while(1) ... if ... break end pattern.

Ungolfed

function s = findFirstPalindromeFactor(n)
  f = 1;                        % factor
  s = '01';                     % non-palindromic string for first try
  while( all(s ~= fliplr(s)) )  % test s not palindrome
    s = num2str( n * f );       % factor of input as string
    f = f + 1;                  % next factor
  end


答:
VBA Excel, <s>150 bytes</s> 146 bytes

Instruction:

Create a workbook with two blank worksheets: Sheet1 and Sheet2. Set the input in Sheet1 and then put the following code in the Sheet1 code module

```<code>Sub A:For Each C In UsedRange:If C.Value="#"Then Sheet2.Range(C.Address)="#"
Next:For Each C In Sheet2.UsedRange:Range(C.Address)="#":Next:End Sub
</code>```

Ungolfed the code:

```<code>Sub A()

For Each C In UsedRange
    If C.Value = "#" Then Sheet2.Range(C.Address) = "#"
Next

For Each C In Sheet2.UsedRange
    Range(C.Address) = "#"
Next

End Sub
</code>```

Explanation:

Loop through every cell in the used range Sheet1

Set the conditional statement to copy every cell contains character hashtag (#) in the used range Sheet1 and paste it to the cell in Sheet2 with the same address as Sheet1.

Loop through once again every cell in the used range Sheet2 to copy every cell address in it and then use it to assign character hashtag (#) to the cell in Sheet1 with the same address as the used range Sheet2.

Example I/O:

Caveat: Make sure every cell in Sheet2 always blank every time you run the program.

Body:
VBA Excel, <s>150 bytes</s> 146 bytes

Instruction:

Create a workbook with two blank worksheets: Sheet1 and Sheet2. Set the input in Sheet1 and then put the following code in the Sheet1 code module

Sub A:For Each C In UsedRange:If C.Value="#"Then Sheet2.Range(C.Address)="#"
Next:For Each C In Sheet2.UsedRange:Range(C.Address)="#":Next:End Sub

Ungolfed the code:

Sub A()

For Each C In UsedRange
    If C.Value = "#" Then Sheet2.Range(C.Address) = "#"
Next

For Each C In Sheet2.UsedRange
    Range(C.Address) = "#"
Next

End Sub

Explanation:

Loop through every cell in the used range Sheet1

Set the conditional statement to copy every cell contains character hashtag (#) in the used range Sheet1 and paste it to the cell in Sheet2 with the same address as Sheet1.

Loop through once again every cell in the used range Sheet2 to copy every cell address in it and then use it to assign character hashtag (#) to the cell in Sheet1 with the same address as the used range Sheet2.

Example I/O:

Caveat: Make sure every cell in Sheet2 always blank every time you run the program.


答:
PowerShell v2+, 72 bytes

```<code>for($i=$n=$args[0];;$i+=$n){if($i-eq-join"$i"["$i".Length..0]){$i;exit}}
</code>```

Long because of how reversing is handled in PowerShell -- not very well. ;-)

Takes input $args[0], stores into $i (our loop variable) and $n (our input). Loops infinitely, incrementing $i by $n each time (to guarantee divisibility).

Each iteration, we check whether $i is a palindrome. There's some trickery happening here, so let me explain. We first take $i and stringify it with "$i". That's then array-indexed in reverse order ["$i".length..0] before being -joined back into a string. That's fed into the right-hand side of the -equality operator, which implicitly casts the string back into an [int], since that's the left-hand operand. Note: this casting does strip any leading zeros from the palindrome, but since we're guaranteed the input isn't divisible by 10, that's OK.

Then, if it is a palindrome, we simply place $i onto the pipeline and exit. Output is implicit at the end of execution.

Test Cases

```<code>PS C:\Tools\Scripts\golfing> 1,2,16,17,42,111,302,1234|%{"$_ -> "+(.\smallest-palindrome-divisible-by-input.ps1 $_)}
1 -> 1
2 -> 2
16 -> 272
17 -> 272
42 -> 252
111 -> 111
302 -> 87278
1234 -> 28382
</code>```

Body:
PowerShell v2+, 72 bytes

for($i=$n=$args[0];;$i+=$n){if($i-eq-join"$i"["$i".Length..0]){$i;exit}}

Long because of how reversing is handled in PowerShell -- not very well. ;-)

Takes input $args[0], stores into $i (our loop variable) and $n (our input). Loops infinitely, incrementing $i by $n each time (to guarantee divisibility).

Each iteration, we check whether $i is a palindrome. There's some trickery happening here, so let me explain. We first take $i and stringify it with "$i". That's then array-indexed in reverse order ["$i".length..0] before being -joined back into a string. That's fed into the right-hand side of the -equality operator, which implicitly casts the string back into an [int], since that's the left-hand operand. Note: this casting does strip any leading zeros from the palindrome, but since we're guaranteed the input isn't divisible by 10, that's OK.

Then, if it is a palindrome, we simply place $i onto the pipeline and exit. Output is implicit at the end of execution.

Test Cases

PS C:\Tools\Scripts\golfing> 1,2,16,17,42,111,302,1234|%{"$_ -> "+(.\smallest-palindrome-divisible-by-input.ps1 $_)}
1 -> 1
2 -> 2
16 -> 272
17 -> 272
42 -> 252
111 -> 111
302 -> 87278
1234 -> 28382


问:
Text animation format Code Golf
Working with old files from DOS, I found an ancient text animation format, that specify how much time each frame must be shown in the screen. It's very simple:

F1W5F2W3

This example above indicates that Frame 1 must be shown for 5 units of time, and frame 2 for 3 units more. Now I want to convert it to:

1, 1, 1, 1, 1, 2, 2, 2

In the converted example below, frame 1 is repeated 5 times, and frame 2 three times.

Rules: The only allowed letters are F and W (and the lowercase counterparts, f and w). Numbers can go up to 255. Total input String with no more than 255 chars.

Other examples:

Input: F10W3F11W3F10W3F12W3

Output: 10, 10, 10, 11, 11, 11, 10, 10, 10, 12, 12, 12

Input: f1w0f2w10

Output: 2, 2, 2, 2, 2, 2, 2, 2, 2, 2

Short code wins.

Edited - Accepted formats:
Any answer containing the output and ignoring spaces. Ex: 1, 1, 2, 2 or [1,1,2,2] or (1,1,2,2). But NOT 1 1 2 2 or [1; 1; 2; 2] or [1 1 2 2].

答:
Retina, 51 bytes

Might be able to be golfed further, I'm not super familiar with Retina.

```<code>i`F(\d+)W(\d+)
$1_$2$*n
(?<=(\d+).*?)n
$1,
\d+_|,$

</code>```

The trailing linefeed is significant.

Try it online!

Explanation:

The code consists of three replacement stages.

```<code>i`F(\d+)W(\d+)
$1_$2$*n
</code>```

This replaces each group of FxWy into x_ followed by n repeated y times. For example, F2W3 is replaced with 2_nnn. i` makes the regex case insensitive.

```<code>(?<=(\d+).*?)n
$1,
</code>```

This matches all the repeated n's. and replaces each of them with the number closest before it, followed by a comma. Using our previous example of F2W3, 2_nnn is replaced with 2_2,2,2,.

```<code>\d+_|,$

</code>```

This removes the final garbage left behind. It replaces the numbers directly followed by underscores, and the comma at the end of the line, with nothing. So 2_2,2,2, becomes 2,2,2, which is the desired output.

Title: Text animation format Code Golf

Body:
Retina, 51 bytes

Might be able to be golfed further, I'm not super familiar with Retina.

i`F(\d+)W(\d+)
$1_$2$*n
(?<=(\d+).*?)n
$1,
\d+_|,$

The trailing linefeed is significant.

Try it online!

Explanation:

The code consists of three replacement stages.

i`F(\d+)W(\d+)
$1_$2$*n

This replaces each group of FxWy into x_ followed by n repeated y times. For example, F2W3 is replaced with 2_nnn. i` makes the regex case insensitive.

(?<=(\d+).*?)n
$1,

This matches all the repeated n's. and replaces each of them with the number closest before it, followed by a comma. Using our previous example of F2W3, 2_nnn is replaced with 2_2,2,2,.

\d+_|,$

This removes the final garbage left behind. It replaces the numbers directly followed by underscores, and the comma at the end of the line, with nothing. So 2_2,2,2, becomes 2,2,2, which is the desired output.


问:
Find the minimum and maximum integers in an array, without using builtins

Challenge

Given an array of integers, received from stdin, function arguments, program arguments, or some other method:

Output only the minimum and maximum numbers in the array, through a return value, stdout, or other fitting methods.

Example session

```<code>> minmax( {0, 15, 2, 3, 7, 18, -2, 9, 6, -5, 3, 8, 9, -14} )
-14 18
</code>```

Reference implementation

```<code>// C++14

void minmax(std::vector<int> v) {
    int min = v[0]; int max = v[0];
    for(auto it : v) {
        if (*it < min)
            min = *it;
        if (*it > max)
            max = *it;
    }
    std::cout << min << ' ' << max << std::endl;
}
</code>```

Rules

You may not use a built-in function to calculate the values.

Standard loopholes disallowed.

Creative implementations encouraged.

This is code-golf, shortest answer wins but will not be selected.

Clarifications

If the array contains 1 element you need to output it twice.

If the minimum and maximum values are the same, you need to output them both.

答:
Scala, 55 bytes

```<code>val s=args.map(_.toInt).sorted
print(s.head+" "+s.last)
</code>```

To execute:

$ scala minmax.scala 1 2 3 4 5 6 7 8 9

Body:
Scala, 55 bytes

val s=args.map(_.toInt).sorted
print(s.head+" "+s.last)

To execute:

$ scala minmax.scala 1 2 3 4 5 6 7 8 9


答:
GolfScript (124 chars)

```<code>10:&,~]'    0.0'*40,{n\:I&/'.'I&%&,{'   '\I&*+&8?:^*100/:x^54,-2%{:i*x.{*^/}:$~$i).)*/^\-}/$3989423$15000500+`5<(49-'.'@}%}/
</code>```

Note: the only whitespace in there are two tab characters. MarkDown is turning them into triple-spaces.

The interesting part (i.e. the calculation) is done in x.8 fixpoint using identity 26.2.10 of Abramowitz and Stegun (1972). The program runs in under 2 seconds on my machine.

Title: Normal distribution values

Body:
Write the shortest program possible which outputs a table of Normal distribution values

```<code>phi(z) = Integral[t from -infty to z of e^(-t^2/2) /sqrt(2 pi) dt]
</code>```

for z from 0.00 to 3.99, giving values accurate to 4 decimal places.

The canonical format for such a table appears to be:

```<code>    0.00    0.01    0.02    0.03    0.04    0.05    0.06    0.07    0.08    0.09
0.0 0.5000  0.5040  0.5080  0.5120  0.5160  0.5199  0.5239  0.5279  0.5319  0.5359
0.1 0.5398  0.5438  0.5478  0.5517  0.5557  0.5596  0.5636  0.5675  0.5714  0.5753
0.2 0.5793  0.5832  0.5871  0.5910  0.5948  0.5987  0.6026  0.6064  0.6103  0.6141
0.3 0.6179  0.6217  0.6255  0.6293  0.6331  0.6368  0.6406  0.6443  0.6480  0.6517
0.4 0.6554  0.6591  0.6628  0.6664  0.6700  0.6736  0.6772  0.6808  0.6844  0.6879
0.5 0.6915  0.6950  0.6985  0.7019  0.7054  0.7088  0.7123  0.7157  0.7190  0.7224
0.6 0.7257  0.7291  0.7324  0.7357  0.7389  0.7422  0.7454  0.7486  0.7517  0.7549
0.7 0.7580  0.7611  0.7642  0.7673  0.7704  0.7734  0.7764  0.7794  0.7823  0.7852
0.8 0.7881  0.7910  0.7939  0.7967  0.7995  0.8023  0.8051  0.8078  0.8106  0.8133
0.9 0.8159  0.8186  0.8212  0.8238  0.8264  0.8289  0.8315  0.8340  0.8365  0.8389
1.0 0.8413  0.8438  0.8461  0.8485  0.8508  0.8531  0.8554  0.8577  0.8599  0.8621
1.1 0.8643  0.8665  0.8686  0.8708  0.8729  0.8749  0.8770  0.8790  0.8810  0.8830
1.2 0.8849  0.8869  0.8888  0.8907  0.8925  0.8944  0.8962  0.8980  0.8997  0.9015
1.3 0.9032  0.9049  0.9066  0.9082  0.9099  0.9115  0.9131  0.9147  0.9162  0.9177
1.4 0.9192  0.9207  0.9222  0.9236  0.9251  0.9265  0.9279  0.9292  0.9306  0.9319
1.5 0.9332  0.9345  0.9357  0.9370  0.9382  0.9394  0.9406  0.9418  0.9429  0.9441
1.6 0.9452  0.9463  0.9474  0.9484  0.9495  0.9505  0.9515  0.9525  0.9535  0.9545
1.7 0.9554  0.9564  0.9573  0.9582  0.9591  0.9599  0.9608  0.9616  0.9625  0.9633
1.8 0.9641  0.9649  0.9656  0.9664  0.9671  0.9678  0.9686  0.9693  0.9699  0.9706
1.9 0.9713  0.9719  0.9726  0.9732  0.9738  0.9744  0.9750  0.9756  0.9761  0.9767
2.0 0.9772  0.9778  0.9783  0.9788  0.9793  0.9798  0.9803  0.9808  0.9812  0.9817
2.1 0.9821  0.9826  0.9830  0.9834  0.9838  0.9842  0.9846  0.9850  0.9854  0.9857
2.2 0.9861  0.9864  0.9868  0.9871  0.9875  0.9878  0.9881  0.9884  0.9887  0.9890
2.3 0.9893  0.9896  0.9898  0.9901  0.9904  0.9906  0.9909  0.9911  0.9913  0.9916
2.4 0.9918  0.9920  0.9922  0.9925  0.9927  0.9929  0.9931  0.9932  0.9934  0.9936
2.5 0.9938  0.9940  0.9941  0.9943  0.9945  0.9946  0.9948  0.9949  0.9951  0.9952
2.6 0.9953  0.9955  0.9956  0.9957  0.9959  0.9960  0.9961  0.9962  0.9963  0.9964
2.7 0.9965  0.9966  0.9967  0.9968  0.9969  0.9970  0.9971  0.9972  0.9973  0.9974
2.8 0.9974  0.9975  0.9976  0.9977  0.9977  0.9978  0.9979  0.9979  0.9980  0.9981
2.9 0.9981  0.9982  0.9982  0.9983  0.9984  0.9984  0.9985  0.9985  0.9986  0.9986
3.0 0.9987  0.9987  0.9987  0.9988  0.9988  0.9989  0.9989  0.9989  0.9990  0.9990
3.1 0.9990  0.9991  0.9991  0.9991  0.9992  0.9992  0.9992  0.9992  0.9993  0.9993
3.2 0.9993  0.9993  0.9994  0.9994  0.9994  0.9994  0.9994  0.9995  0.9995  0.9995
3.3 0.9995  0.9995  0.9995  0.9996  0.9996  0.9996  0.9996  0.9996  0.9996  0.9997
3.4 0.9997  0.9997  0.9997  0.9997  0.9997  0.9997  0.9997  0.9997  0.9997  0.9998
3.5 0.9998  0.9998  0.9998  0.9998  0.9998  0.9998  0.9998  0.9998  0.9998  0.9998
3.6 0.9998  0.9998  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999
3.7 0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999
3.8 0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999
3.9 1.0000  1.0000  1.0000  1.0000  1.0000  1.0000  1.0000  1.0000  1.0000  1.0000
</code>```

Body:
GolfScript (124 chars)

10:&,~]'    0.0'*40,{n\:I&/'.'I&%&,{'   '\I&*+&8?:^*100/:x^54,-2%{:i*x.{*^/}:$~$i).)*/^\-}/$3989423$15000500+`5<(49-'.'@}%}/

Note: the only whitespace in there are two tab characters. MarkDown is turning them into triple-spaces.

The interesting part (i.e. the calculation) is done in x.8 fixpoint using identity 26.2.10 of Abramowitz and Stegun (1972). The program runs in under 2 seconds on my machine.


答:
05AB1E, <s>70</s> <s>68</s> <s>69</s> <s>61</s> <s>58</s> <s>60</s> 40 bytes

```<code>€S`¹gG~}Dg©L*0KŸ<U¹v¼y1åi®FXNå}ë0®×}J}¾ä
</code>```

Explanation

```<code>€S`                                       # split each string in input to a charlist and place separately on stack
   ¹gG~}                                  # OR the char arrays to produce a single list with 1's in the columns that have 1's and 0 in the rest
        Dg L*                             # multiply by indices (1-indexed)
          ©                               # store row length in register
             0K                           # remove 0's (the indices which should not have 1's
               Ÿ<U                        # store a list of the indices that should have 1's in X
                  ¹v                 }    # for each string in input
                    ¼                     # increase counter
                     y1åi      ë   }      # if the row contains at least one 1
                         ®FXNå}           # push 1 for indices which should have 1 and else 0
                                0®×       # else push a row of 0's
                                    J     # join into a string
                                      ¾ä  # split the string in rows
</code>```

Try it online

Body:
You're given a rectangular grid of the characters . and #, like this:

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

Your task is to fill the entire axis-aligned bounding box of the # with further #:

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

The axis-aligned bounding box is the smallest rectangle which contains all the #.

Want more? Try Part II!

Rules

You may use any two distinct printable ASCII characters (0x20 to 0x7E, inclusive), in place of # and .. I'll continue referring to them as # and . for the remainder of the specification though.

Input and output may either be a single linefeed-separated string or a list of strings (one for each line), but the format has to be consistent.

You may assume that the input contains at least one # and all lines are the same length.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

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

Test Cases

Each test case has input and output next to each other.

```<code>#    #

...    ...
#..    #..
...    ...

...    ...
#..    ###
..#    ###

.#.    ###
#..    ###
..#    ###

.....    .....
.#.#.    .###.
.....    .....

...    ...
.#.    .#.
...    .#.
.#.    .#.
...    ...

..........    ..........
..........    ..........
....#.....    ....#.....
..........    ..........

..........    ..........
..........    ..........
....#.....    ...##.....
...#......    ...##.....

..........    ..........
..#.......    ..###.....
....#.....    ..###.....
...#......    ..###.....

..........    ..........
..#.......    ..######..
....#..#..    ..######..
...#......    ..######..

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

Body:
05AB1E, <s>70</s> <s>68</s> <s>69</s> <s>61</s> <s>58</s> <s>60</s> 40 bytes

€S`¹gG~}Dg©L*0KŸ<U¹v¼y1åi®FXNå}ë0®×}J}¾ä

Explanation

€S`                                       # split each string in input to a charlist and place separately on stack
   ¹gG~}                                  # OR the char arrays to produce a single list with 1's in the columns that have 1's and 0 in the rest
        Dg L*                             # multiply by indices (1-indexed)
          ©                               # store row length in register
             0K                           # remove 0's (the indices which should not have 1's
               Ÿ<U                        # store a list of the indices that should have 1's in X
                  ¹v                 }    # for each string in input
                    ¼                     # increase counter
                     y1åi      ë   }      # if the row contains at least one 1
                         ®FXNå}           # push 1 for indices which should have 1 and else 0
                                0®×       # else push a row of 0's
                                    J     # join into a string
                                      ¾ä  # split the string in rows

Try it online


问:
Create an unlimited counterstring
A counterstring is some sort of self-describing test data that is used in software testing. Not sure it was actually invented by James Bach, but I know it from there.

The idea is as follows: the test data contains many asterisk (*). The number in front of the asterisk tells you how long the test data is at that point. If you need to know a position in the test data that is not an asterisk, find the last asterisk, look at the number before and add the number of digits that follow.

The sequence starts like this:

```<code>2*4*6*8*11*14*17*20*23*
             ^
</code>```

As you can see, the marked asterisk is at position 14.

If a file happens to be truncated as follows

```<code>[...]2045*20
</code>```

then you can derive that there is a limit of 2047 characters somewhere (2045 where the asterisk is plus 2 for 2 and 0).

It's your task to create the shortest (this is code-golf) program that outputs (std::out or file or whatever) an arbitrary long test string of that format. The length in characters is given as argument. The program shall support up to 2 GB test data (input value 2147483647 characters).

"Dangerous" positions in the 2 GB file:

```<code>8*11*
98*102*
998*1003*
9998*10004*
99998*100005*
999995*1000003*
9999995*10000004*
99999995*100000005*
999999995*1000000006*
</code>```

This should answer @Leaky Nun's question if there is a decision to make between 995*999* and 995*1000* or similar: no.

The end of the 2 GB file with input value 2147483647 is:

```<code>2147483640*2147483
</code>```

Title: Create an unlimited counterstring

Body:
R, 92 bytes

    N=nchar;f=function(n){z=0;y="";while(z<n){z=z+N(z+N(z)+1)+1;y=paste0(y,z,"*")};strtrim(y,n)}

Example output:

f(103)
  [1] "2*4*6*8*11*14*17*20*23*26*29*32*35*38*41*44*47*50*53*56*59*62*65*68*71*74*77*80*83*86*89*92*95*98*102*1"


答:
PHP, 67 bytes

Space as separator

PHP5 using deprecated ereg_replace function.

```<code>for(;++$i<128;)echo ereg_replace("[^".chr($i)."]","",$argv[1])." ";
</code>```

PHP7, 73 bytes

```<code>for(;++$i<128;)echo str_repeat($j=chr($i),substr_count($argv[1],$j))." ";
</code>```

Using built in is worse :(

```<code>foreach(array_count_values(str_split($argv[1]))as$a=>$b)echo str_repeat($a,$b)." ";
</code>```

Title: Exploded view of a string

Body:
PHP, 67 bytes

Space as separator

PHP5 using deprecated ereg_replace function.

for(;++$i<128;)echo ereg_replace("[^".chr($i)."]","",$argv[1])." ";

PHP7, 73 bytes

for(;++$i<128;)echo str_repeat($j=chr($i),substr_count($argv[1],$j))." ";

Using built in is worse :(

foreach(array_count_values(str_split($argv[1]))as$a=>$b)echo str_repeat($a,$b)." ";


答:
Haskell, <s>102</s> <s>100</s> <s>96</s> <s>91</s> 87 bytes

```<code>c s=unlines.f$f.(#)where f=(<$>[1..s]);x#y|elem y[1,s,x]||elem x[1,s,s-y+1]='*'|1>0=' '
</code>```

Saved 2 bytes, thanks to flawr.

Saved 4 more bytes by using list comprehensions.

5 bytes saved combining flawr's improvement with any

4 bytes saved by replacing any with elem

Ungolfed version:

```<code>cross :: Int -> String
cross s = unlines $ map line [1..s]
    where line y = map (pos y) [1..s]
          pos y x | x == y = '*'
                  | x == s - y + 1 = '*'
                  | y `elem` [1, s] = '*'
                  | x `elem` [1, s] = '*'
                  | otherwise = ' '
</code>```

I'm sure this can still be improved, but this is what I've come up with for now.

Old version:

```<code>c s=unlines.f$f.(#)where f=(<$>[1..s]);x#y|any(==y)[1,s,x]||any(==x)[1,s,s-y+1]='*'|1>0=' '
</code>```

Title: Creating a Crossed Square

Body:
Creating a Crossed Square

You are to take input of an integer of one or more and output a square made of any printable character of your choice with a diagonal cross through the centre.

The general idea is for the output to be a hollow square that has a diagonal cross through it.:

```<code>Input: 7
Output:
*******
*#   #*
* # # *
*  #  *
* # # *
*#   #*
*******
</code>```

In the above example the '*'s represent the outer box and the '#'s represent the diagonal cross.

Note that the above example uses two different characters so that it is easier to see what the output looks like, your program should use one character only.

Input

An integer of 1 or more, it is guaranteed to be odd.

Output

A square that is made up of a character of your choice with a cross through the middle.

The cross must be diagonal

The square may be output via the function or written to output

Trailing newlines are okay

Can output as a graphic, diagram or image if you wish too

Examples

```<code>Input: 1
Output:
*

Input: 3
Output:
***
***
***

Input: 5
Output:
*****
** **
* * *
** **
*****

Input: 7
Output:
*******
**   **
* * * *
*  *  *
* * * *
**   **
*******
</code>```

Specs

Functions or full programs are allowed

You can get input by your preferred means

Standard loopholes are disallowed

Programs must work without any additional statements i.e. usings in C#, they must be included in the entry

You can output from a function or print the result

This is code golf so the shortest solution wins.

Body:
Haskell, <s>102</s> <s>100</s> <s>96</s> <s>91</s> 87 bytes

c s=unlines.f$f.(#)where f=(<$>[1..s]);x#y|elem y[1,s,x]||elem x[1,s,s-y+1]='*'|1>0=' '

Saved 2 bytes, thanks to flawr.

Saved 4 more bytes by using list comprehensions.

5 bytes saved combining flawr's improvement with any

4 bytes saved by replacing any with elem

Ungolfed version:

cross :: Int -> String
cross s = unlines $ map line [1..s]
    where line y = map (pos y) [1..s]
          pos y x | x == y = '*'
                  | x == s - y + 1 = '*'
                  | y `elem` [1, s] = '*'
                  | x `elem` [1, s] = '*'
                  | otherwise = ' '

I'm sure this can still be improved, but this is what I've come up with for now.

Old version:

c s=unlines.f$f.(#)where f=(<$>[1..s]);x#y|any(==y)[1,s,x]||any(==x)[1,s,s-y+1]='*'|1>0=' '


问:
How does math work in Anastasiya's world?

Background:

Standard operation math like basic addition and multiplication in the real world work like these:

```<code>12 + 123 = 135
</code>```

and

```<code>12 * 123 = 1476
</code>```

That's not interesting and boring! Many schools are already interpreting this as practice, practice, practice of formal algorithms. That implies a pretty rigid and boring mathematical diet and is not what is intended in this challenge. Get ready to play some fun on our beloved site.

Consider the process of adding two positive integer numbers, then adding again all the digits of its result. Repeating with the addition until only a single digit is obtained. For example:

The result of 12 + 123 is 135.

Adding all the digits of 135 we obtain 1 + 3 + 5 = 9.

The number of steps required to obtain a single digit value 9 in this repeated addition is 2.

As with the previous process of the addition, the multiplication of two positive integer numbers follows the same process. Multiply all the digits of its result and then repeating this process until only a single digit remains. Take the above example:

The result of 12 * 123 is 1476.

Multiply all the digits of 1476 we obtain 1 * 4 * 7 * 6 = 168.

Multiply again all the digits of 168 we obtain 1 * 6 * 8 = 48.

Multiply again all the digits of 48 we obtain 4 * 8 = 32.

Multiply once again all the digits of 32 we obtain 3 * 2 = 6.

The number of steps required to obtain a single digit value 6 this repeated multiplication is 5.

For this challenge's sake and avoiding any misuse of math notations, I introduce these two dummy notations: (+) and (*), but you may use any notation you like, which work like the followings:

The operation of repeated addition process to obtain a single value is 12 (+) 123 = 9.

The operation of repeated multiplication process to obtain a single value is 12 (*) 123  = 6.

Challenge:

The challenge is to write either a program or a function which can perform both of operations as explained in the background section: (+) and (*).

Input:

The inputs of the program or the function are two positive integers and one operation either (+) and (*). The format of the input is an arbitrary choice of the programmer. You may format the input, for example, a (+) b or F(a, (+), b) or any format you wish.

Output:

The output of the program or the function must contain the result of operation and the number of steps required with freestyle format as you wish.

Test Cases (ignore the input and output format):

```<code>    81 (+) 31       -->   (4 ; 2)
    351 (+) 14568   -->   (6 ; 3)
    21 (*) 111      -->   (8 ; 3)
    136 (*) 2356    -->   (0 ; 2)
</code>```

General rules:

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

Don't let esolangs discourage you from posting an answer with regular languages. Enjoy this challenge by providing an answer as short as possible with your programming language. If you post a clever answer and a clear explanation, your answer will be appreciated (hence the upvotes) regardless of the programming language you use.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/ method with the proper parameters, full programs, etc. The choice is yours.

If possible, your program can properly handle large numbers. If not, that will just be fine.

Let the game begin!!

答:
ARM Machine Code, 48 bytes

Hex dump:

```<code>b570 2a00 bf0c 1840 4348 2101 230a e00c 3101 0015 fbb0 f6f3 fb06 0413 2a00 bf0c 192d 4365 0030 d1f5 0028 280a d2f0 bd70
</code>```

This function doesn't depend any system calls or library functions. This is Thumb-2 code, which is a variable-length instruction encoding (2 or 4 bytes) for 32-bit ARM. Thus, the maximum value it can process is 2^32-1. 2 bytes could be dropped if it didn't conform to the AAPCS (46 bytes), since we wouldn't have to stack registers at the beginning.

Ungolfed assembly (GNU syntax):

```<code>.syntax unified
.text
.global anastasiya
.thumb_func
anastasiya:
    @Input:
    @r0 - First number
    @r1 - Second number
    @r2 - 0 for add, 1 for multiply
    @Output:
    @r0 - Resultant value
    @r1 - Number of steps
    push {r4,r5,r6,lr}
    cmp r2,#0
    ite eq @if r2==0
    addeq r0,r0,r1 @r0+=r1
    mulne r0,r0,r1 @else r0*=r1
    movs r1,#1 @r1 is the number of steps
    movs r3,#10
    b endloop
    loop:
        adds r1,r1,#1 @Increment number of steps
        movs r5,r2 @r5=1 if multiply, 0 if add
        parseDigits:
            udiv r6,r0,r3 @r6=r0/r3
            mls r4,r6,r3,r0 @r4=r0 - r6*r3
            @Last two operations were r4=r0%r3 (r3==10)
            cmp r2,#0
            ite eq @if r2==0
            addeq r5,r5,r4 @r5+=r4
            mulne r5,r5,r4 @else r5*=r4
            movs r0,r6 @r0=r6 (Set r0 to r0/10)
            bne parseDigits @while (r0!=0)
        @Now our new total is in r5
        movs r0,r5 @Put it in r0
    endloop:
        cmp r0,#10
        bhs loop @while (r0 >=10)
    pop {r4,r5,r6,pc} @Return
</code>```

Testing script in C:

```<code>#include <stdio.h>
unsigned long long anastasiya(unsigned,unsigned,unsigned);

int main(void) {
    unsigned x,y,op;
    printf("Enter first operand, second operand, and 0 for addition or 1 for multiplication.\n");
    scanf("%u%u%u",&x,&y,&op);
    unsigned long long res = anastasiya(x,y,op);
    printf("Result = %u, steps = %u\n",(unsigned)res ,(unsigned)(res >> 32));
}
</code>```

Body:
ARM Machine Code, 48 bytes

Hex dump:

b570 2a00 bf0c 1840 4348 2101 230a e00c 3101 0015 fbb0 f6f3 fb06 0413 2a00 bf0c 192d 4365 0030 d1f5 0028 280a d2f0 bd70

This function doesn't depend any system calls or library functions. This is Thumb-2 code, which is a variable-length instruction encoding (2 or 4 bytes) for 32-bit ARM. Thus, the maximum value it can process is 2^32-1. 2 bytes could be dropped if it didn't conform to the AAPCS (46 bytes), since we wouldn't have to stack registers at the beginning.

Ungolfed assembly (GNU syntax):

.syntax unified
.text
.global anastasiya
.thumb_func
anastasiya:
    @Input:
    @r0 - First number
    @r1 - Second number
    @r2 - 0 for add, 1 for multiply
    @Output:
    @r0 - Resultant value
    @r1 - Number of steps
    push {r4,r5,r6,lr}
    cmp r2,#0
    ite eq @if r2==0
    addeq r0,r0,r1 @r0+=r1
    mulne r0,r0,r1 @else r0*=r1
    movs r1,#1 @r1 is the number of steps
    movs r3,#10
    b endloop
    loop:
        adds r1,r1,#1 @Increment number of steps
        movs r5,r2 @r5=1 if multiply, 0 if add
        parseDigits:
            udiv r6,r0,r3 @r6=r0/r3
            mls r4,r6,r3,r0 @r4=r0 - r6*r3
            @Last two operations were r4=r0%r3 (r3==10)
            cmp r2,#0
            ite eq @if r2==0
            addeq r5,r5,r4 @r5+=r4
            mulne r5,r5,r4 @else r5*=r4
            movs r0,r6 @r0=r6 (Set r0 to r0/10)
            bne parseDigits @while (r0!=0)
        @Now our new total is in r5
        movs r0,r5 @Put it in r0
    endloop:
        cmp r0,#10
        bhs loop @while (r0 >=10)
    pop {r4,r5,r6,pc} @Return

Testing script in C:

#include <stdio.h>
unsigned long long anastasiya(unsigned,unsigned,unsigned);

int main(void) {
    unsigned x,y,op;
    printf("Enter first operand, second operand, and 0 for addition or 1 for multiplication.\n");
    scanf("%u%u%u",&x,&y,&op);
    unsigned long long res = anastasiya(x,y,op);
    printf("Result = %u, steps = %u\n",(unsigned)res ,(unsigned)(res >> 32));
}