问:
Calculate the sum of ILD

Input:

An integer

Output:

Sum of the input itself + the length of the input + each individual digit of the input.

```<code>nr + nr-length + {sum of digits} = output
</code>```

Examples:

Input: 99

Output: 99 (nr) + 2 (nr-length) + (9 + 9) (digits) → 119

Input: 123

Output: 123 + 3 + (1 + 2 + 3) → 132

Challenge rules:

The input can also contain negative input, which are resolved special. The -/minus-sign is also +1 for the length, and is part of the first digit.

For example:

Input: -123

Output: -123 + 4 + (-1 + 2 + 3) → -115

You can assume that the input nor output will ever be outside the range of an (32-bit) integer.

General rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases:

```<code>87901 → 87931
123 → 132
99 → 119
5 → 11
1 → 3
0 → 1
-3 → -4
-123 → -115
-900 → -905
-87901 → -87886
</code>```

Semi-related: Count Sum of all Digits

答:
Perl, 27 bytes

22 bytes code + 5 for -paF.

$"="+";$_+=@F+eval"@F"
```

<h3>Explanation</h3>

<p>Uses the <code>-a</code> autosplit option with an empty delimiter (<code>-F</code>) creating an array of the digits passed in. Uses the magic variable <code>$"</code> which controls which char is used to join an array when it's interpolated into a string (we use <code>"+"</code> here) and the fact that a list used in scalar context will return the length of the list (the number of digits).</p>

<h3>Usage</h3>

<pre class="lang-sh prettyprint-override"><code>echo -n 99 | perl -paF -e'$"="+";$_+=@F+eval"@F"'
119
</code>```

Perl, 27 bytes

22 bytes code + 5 for -paF.

Alternative solution, that's a lot more readable for no more bytes. I prefer the other as it looks more cryptic!

$_+=@F+eval join"+",@F
```

Title: Calculate the sum of ILD

Body:
Perl, 27 bytes

22 bytes code + 5 for -paF.

$"="+";$_+=@F+eval"@F"

Explanation

Uses the -a autosplit option with an empty delimiter (-F) creating an array of the digits passed in. Uses the magic variable $" which controls which char is used to join an array when it's interpolated into a string (we use "+" here) and the fact that a list used in scalar context will return the length of the list (the number of digits).

Usage

echo -n 99 | perl -paF -e'$"="+";$_+=@F+eval"@F"'
119

Perl, 27 bytes

22 bytes code + 5 for -paF.

Alternative solution, that's a lot more readable for no more bytes. I prefer the other as it looks more cryptic!

$_+=@F+eval join"+",@F


问:
Is case sensitivity important? Part II: reality check
In this question Tom learned that, in general, there are many motivations to choose to include case sensitivity in his programming language, because the possible combinations for a variable name are much more than what's possible with a case insensitive programming language for a name of the same length.

But, as a more meticulous person than him pointed out, even with case sensitivity, many combinations like A_18__cDfG are wasted anyway because no one will ever use them, so Tom decided to be an even more meticulous person and to redo the calculation of the difference of possibilities of variable names between a case sensitive programming language and a case insensitive programming language only counting the variable names that are likely to be used.

The Challenge

Write a function (or a full program if your language doesn't support them) that takes an input n and returns (or outputs) the difference between the number of possible, valid combinations for a variable name of length n with case sensitivity and a variable name of the same length without case sensitivity.

Valid names

You must only count names in which:

The first character is either an alphabet letter or an underscore, but never a digit;

If there are digits, they must appear at the end of the name, so that x1 and arraysize12 are valid but iam6feettall isn't;

If underscores are present, they must appear at the beginning of the name, like in __private and _VERSION but unlike in __init__ or some_variable;

For case sensitive names, variables like HeLlObOyS aren't counted. A name must be either all uppercase (HELLOBOYS) or all lowercase (helloboys);

There must be at least one alphabetic character. This means _________a9999999999 is valid but __ or _4 arent't.

Rules

Regexs are, of course, allowed;

Blame Tom's meticulousness.

Testcases

```<code>Input (lenght of the varable name) -> Output (differences in valid combinations)
0 -> 0 (no combinations for both cases: 0 - 0 = 0)
1 -> 26
2 -> 962
3 -> 27898
4 -> 754234
5 -> 19898970
6 -> 520262106
</code>```

Scoring

It's again code golf. Shortes program in bytes wins.

Reference, non-competing Lua implementation

Since the test cases may be wrong, I've been asked to include it, so here it is:

```<code>local case = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789"

local function isvalid(s)  --checks if a string s is valid AND only suitable for case sensitive
    if s:upper() == s then --if the string is all uppercase, it's also valid for case unsensitive
        return false
    end
    return (s:match"^_*[%w]+[%d]*$" --checks if it matchs the underscore-character-digit sequence
            and s:lower() == s)     --checks if it's all lowercase
            and true                --trasforms to boolean value
end

local function each(s, n) --recursive function called for character at position 2..n
    if n == 0 then
        if isvalid(s) then
            return 1
        end
        return 0
    else
        local total = 0
        for i = 1, #case do
            total = total + each(s..case:sub(i, i), n - 1)
        end
        return total
    end
end

local function diff(n) --the actual function
    local total = 0
    if n > 0 then
        for s = 1, #case - 10 do --loops for character at position 1, which can't be a digit
            total = total + each(case:sub(s, s), n - 1)
        end
    end
    print(string.format("%.0f", total)) --prints the result in non-scientific notation
end
</code>```

答:
JavaScript (ES7), 55 bytes

```<code>n=>[...Array(n)].reduce(r=>r+26**++i*(10**n---1)/9,i=0)
</code>```

I get the same results as @Zeta does. I started along similar lines although I simplified sum(10**[0..n-i]) to (10**(n+1-i)-1)/9.

ContentLicense: CC BY-SA 3.0

Body:
JavaScript (ES7), 55 bytes

n=>[...Array(n)].reduce(r=>r+26**++i*(10**n---1)/9,i=0)

I get the same results as @Zeta does. I started along similar lines although I simplified sum(10**[0..n-i]) to (10**(n+1-i)-1)/9.


答:
Pyth, <s>25</s> <s>18</s> 16 bytes

```<code>sm*^26ds^LTh-QdS
</code>```

Try it online. Test suite.

I also get the same results as @Zeta.

Title: Is case sensitivity important? Part II: reality check

Body:
In this question Tom learned that, in general, there are many motivations to choose to include case sensitivity in his programming language, because the possible combinations for a variable name are much more than what's possible with a case insensitive programming language for a name of the same length.

But, as a more meticulous person than him pointed out, even with case sensitivity, many combinations like A_18__cDfG are wasted anyway because no one will ever use them, so Tom decided to be an even more meticulous person and to redo the calculation of the difference of possibilities of variable names between a case sensitive programming language and a case insensitive programming language only counting the variable names that are likely to be used.

The Challenge

Write a function (or a full program if your language doesn't support them) that takes an input n and returns (or outputs) the difference between the number of possible, valid combinations for a variable name of length n with case sensitivity and a variable name of the same length without case sensitivity.

Valid names

You must only count names in which:

The first character is either an alphabet letter or an underscore, but never a digit;

If there are digits, they must appear at the end of the name, so that x1 and arraysize12 are valid but iam6feettall isn't;

If underscores are present, they must appear at the beginning of the name, like in __private and _VERSION but unlike in __init__ or some_variable;

For case sensitive names, variables like HeLlObOyS aren't counted. A name must be either all uppercase (HELLOBOYS) or all lowercase (helloboys);

There must be at least one alphabetic character. This means _________a9999999999 is valid but __ or _4 arent't.

Rules

Regexs are, of course, allowed;

Blame Tom's meticulousness.

Testcases

```<code>Input (lenght of the varable name) -> Output (differences in valid combinations)
0 -> 0 (no combinations for both cases: 0 - 0 = 0)
1 -> 26
2 -> 962
3 -> 27898
4 -> 754234
5 -> 19898970
6 -> 520262106
</code>```

Scoring

It's again code golf. Shortes program in bytes wins.

Reference, non-competing Lua implementation

Since the test cases may be wrong, I've been asked to include it, so here it is:

```<code>local case = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789"

local function isvalid(s)  --checks if a string s is valid AND only suitable for case sensitive
    if s:upper() == s then --if the string is all uppercase, it's also valid for case unsensitive
        return false
    end
    return (s:match"^_*[%w]+[%d]*$" --checks if it matchs the underscore-character-digit sequence
            and s:lower() == s)     --checks if it's all lowercase
            and true                --trasforms to boolean value
end

local function each(s, n) --recursive function called for character at position 2..n
    if n == 0 then
        if isvalid(s) then
            return 1
        end
        return 0
    else
        local total = 0
        for i = 1, #case do
            total = total + each(s..case:sub(i, i), n - 1)
        end
        return total
    end
end

local function diff(n) --the actual function
    local total = 0
    if n > 0 then
        for s = 1, #case - 10 do --loops for character at position 1, which can't be a digit
            total = total + each(case:sub(s, s), n - 1)
        end
    end
    print(string.format("%.0f", total)) --prints the result in non-scientific notation
end
</code>```

Body:
Pyth, <s>25</s> <s>18</s> 16 bytes

sm*^26ds^LTh-QdS

Try it online. Test suite.

I also get the same results as @Zeta.


答:
05AB1E, <s>18</s> 14 bytes

```<code>Lv1¹y->×26ym*O
</code>```

Explanation

```<code>Lv               # for each n in range(1,input)
  1¹y->×         # push 1 repeated (input-n+1) nr of times
        26ym     # 26^n
            *    # multiply the ones by the power of 26
             O   # sum and implicitly print
</code>```

Try it online

Body:
05AB1E, <s>18</s> 14 bytes

Lv1¹y->×26ym*O

Explanation

Lv               # for each n in range(1,input)
  1¹y->×         # push 1 repeated (input-n+1) nr of times
        26ym     # 26^n
            *    # multiply the ones by the power of 26
             O   # sum and implicitly print

Try it online


问:
Minimum Scalar Product
Minimum Scalar Product

The inspiration for this code golf problem is from Google's code jam competition. The premise behind the problem is, given the input of two vectors of varying lengths, find the minimum possible scalar. A scalar can be found using the following formula:

```<code>x1 * y1 + x2 * y2 + ... + xn * yn
</code>```

The problem, however, is that multiple values for the scalar can be found depending on the order of the numerals in the input case (seen below). Your goal is to determine the minimum possible scalar integer solution by plugging in the input case numbers into the equation and solving for it. You may use every number in the input only once, and must use all of the numbers.

Allow me to provide an example with the following vectors.

Input

```<code>3
1 3 -5
-2 4 1
</code>```

Output

```<code>-25
</code>```

The first integer on the line represents the number of numbers, n, in each vector. In this case, we have three numbers in each vector.

The number n may vary with each test case, but there will always be two vectors.

In the example input, the minimum scalar product would be -25.

```<code>(-5 * 4) + (1 * 1) + (3 * -2) = 25
</code>```

Rules

You may only use each integer in both vectors once.

You must use all integers in the vectors.

Your output must only include the final product

I'll select the solution with the least amount of code, which follows all of the specifications listed above, in any language!

 Hint: You don't need to brute force this problem, unless it makes your code shorter. There is a specific method involved in finding the minimum spanning scalar :).

答:
Haskell, 59 bytes

```<code>import Data.List
v?u=sum$zipWith(*)(sort v)$reverse$sort u
</code>```

Title: Minimum Scalar Product

Body:
Haskell, 59 bytes

import Data.List
v?u=sum$zipWith(*)(sort v)$reverse$sort u


问:
Runs of Digits in Pi
Your goal is to output the strictly increasing sequence of consecutive, identical digits of pi (π). Each term in the sequence must be one digit longer than the previous. So 3 (0th digit of pi) is the first time a run of digits occurs (length 1). The next to occur is 33 (digits 24 and 25 of pi). Of course, this sequence requires the digits of pi to be in base 10.

The ones known so far, and the first six all occur within the first 800 digits:

```<code>3
33
111
9999
99999
999999
3333333
44444444
777777777
6666666666
... (not in first 2 billion digits)
</code>```

Note that the consecutive nines all occur together, in the same run, so if the next larger run you found happened to be 1000 consecutive 0s, this would fill in multiple terms of the sequence.

I have not found any more terms with my program. I know there are no more terms within the first 50000 digits or more. My program was taking too long with 500000 digits, so I gave up.

Reference Implementation

You may:

Output the sequence forever

Take an integer n and find the first n numbers in the sequence

Take an integer n and find the numbers in the sequence contained in the first n digits of pi.

Make sure to specify which one your code does. The number n may be zero or one indexed.

Inspired by this mathoverflow question.

答:
Python 2, 110 bytes

n=input()
x=p=7*n|1
while~-p:x=p/2*x/p+2*10**n;p-=2
l=m=0
for c in`x`:
 l=l*(p==c)+1;p=c
 if l>m:m=l;print p*l
```

<p>The maximum number of digits to check is taken as from stdin. 10,000 digits finishes in about 2s with PyPy 5.3.</p>

<p><strong>Sample Usage</strong></p>

<pre class="lang-python prettyprint-override"><code>$ echo 10000 | pypy pi-runs.py
3
33
111
9999
99999
999999
</code>```

Something Useful

from sys import argv
from gmpy2 import mpz

def pibs(a, b):
  if a == b:
    if a == 0:
      return (1, 1, 1123)
    p = a*(a*(32*a-48)+22)-3
    q = a*a*a*24893568
    t = 21460*a+1123
    return (p, -q, p*t)
  m = (a+b) >> 1
  p1, q1, t1 = pibs(a, m)
  p2, q2, t2 = pibs(m+1, b)
  return (p1*p2, q1*q2, q2*t1 + p1*t2)

if __name__ == '__main__':
  from sys import argv
  digits = int(argv[1])

  pi_terms = mpz(digits*0.16975227728583067)
  p, q, t = pibs(0, pi_terms)

  z = mpz(10)**digits
  pi = 3528*q*z/t

  l=m=0
  x=0
  for c in str(pi):
   l=l*(p==c)+1;p=c
   if l>m:m=l;print x,p*l
   x+=1
```

<p>I've switched from Chudnovsky to Ramanujan 39 for this. Chudnovsky ran out of memory on my system shortly after 100 million digits, but Ramanujan made it all the way to 400 million, in only about 38 minutes. I think this is another case were slower growth rate of terms wins out in the end, at least on a system with limited resources.</p>

<p><strong>Sample Usage</strong></p>

<pre class="lang-python prettyprint-override"><code>$ python pi-ramanujan39-runs.py 400000000
0 3
25 33
155 111
765 9999
766 99999
767 999999
710106 3333333
22931752 44444444
24658609 777777777
386980421 6666666666
</code>```

Faster Unbounded Generators

The reference implementation given in the problem description is interesting. It uses an unbounded generator, taken directly from the paper Unbounded Spigot Algorithms for the Digits of Pi. According to the author, the implementations provided are "deliberately obscure", so I decided to make fresh implementations of all three algorithms listed by the author, without deliberate obfuscation. I've also added a fourth, based on Ramanujan #39.

try:
  from gmpy2 import mpz
except:
  mpz = long

def g1_ref():
  # Leibniz/Euler, reference
  q, r, t = mpz(1), mpz(0), mpz(1)
  i, j = 1, 3
  while True:
    n = (q+r)/t
    if n*t > 4*q+r-t:
      yield n
      q, r = 10*q, 10*(r-n*t)
    q, r, t = q*i, (2*q+r)*j, t*j
    i += 1; j += 2

def g1_md():
  # Leibniz/Euler, multi-digit
  q, r, t = mpz(1), mpz(0), mpz(1)
  i, j = 1, 3
  z = mpz(10)**10
  while True:
    n = (q+r)/t
    if n*t > 4*q+r-t:
      for d in digits(n, i>34 and 10 or 1): yield d
      q, r = z*q, z*(r-n*t)
    u, v, x = 1, 0, 1
    for k in range(33):
      u, v, x = u*i, (2*u+v)*j, x*j
      i += 1; j += 2
    q, r, t = q*u, q*v+r*x, t*x

def g2_md():
  # Lambert, multi-digit
  q, r, s, t = mpz(0), mpz(4), mpz(1), mpz(0)
  i, j, k = 1, 1, 1
  z = mpz(10)**49
  while True:
    n = (q+r)/(s+t)
    if n == q/s:
      for d in digits(n, i>65 and 49 or 1): yield d
      q, r = z*(q-n*s), z*(r-n*t)
    u, v, w, x = 1, 0, 0, 1
    for l in range(64):
      u, v, w, x = u*j+v, u*k, w*j+x, w*k
      i += 1; j += 2; k += j
    q, r, s, t = q*u+r*w, q*v+r*x, s*u+t*w, s*v+t*x

def g3_ref():
  # Gosper, reference
  q, r, t = mpz(1), mpz(180), mpz(60)
  i = 2
  while True:
    u, y = i*(i*27+27)+6, (q+r)/t
    yield y
    q, r, t, i = 10*q*i*(2*i-1), 10*u*(q*(5*i-2)+r-y*t), t*u, i+1

def g3_md():
  # Gosper, multi-digit
  q, r, t = mpz(1), mpz(0), mpz(1)
  i, j = 1, 60
  z = mpz(10)**50
  while True:
    n = (q+r)/t
    if n*t > 6*i*q+r-t:
      for d in digits(n, i>38 and 50 or 1): yield d
      q, r = z*q, z*(r-n*t)
    u, v, x = 1, 0, 1
    for k in range(37):
      u, v, x = u*i*(2*i-1), j*(u*(5*i-2)+v), x*j
      i += 1; j += 54*i
    q, r, t = q*u, q*v+r*x, t*x

def g4_md():
  # Ramanujan 39, multi-digit
  q, r, s ,t = mpz(0), mpz(3528), mpz(1), mpz(0)
  i = 1
  z = mpz(10)**3511
  while True:
    n = (q+r)/(s+t)
    if n == (22583*i*q+r)/(22583*i*s+t):
      for d in digits(n, i>597 and 3511 or 1): yield d
      q, r = z*(q-n*s), z*(r-n*t)
    u, v, x = mpz(1), mpz(0), mpz(1)
    for k in range(596):
      c, d, f = i*(i*(i*32-48)+22)-3, 21460*i-20337, -i*i*i*24893568
      u, v, x = u*c, (u*d+v)*f, x*f
      i += 1
    q, r, s, t = q*u, q*v+r*x, s*u, s*v+t*x

def digits(x, n):
  o = []
  for k in range(n):
    x, r = divmod(x, 10)
    o.append(r)
  return reversed(o)
```

<p><strong>Notes</strong></p>

<p>Above are 6 implementations: the two reference implementations provided by the author (denoted <code>_ref</code>), and four that compute terms in batches, generating multiple digits at once (<code>_md</code>). All implementations have been confirmed to 100,000 digits. When choosing batch sizes, I chose values that slowly lose precision over time. For example, <code>g1_md</code> generates 10 digits per batch, with 33 iterations. However, this will only produce ~9.93 correct digits. When precision runs out the check condition will fail, triggering an extra batch to be run. This seems to be more performant than slowly gainly extra, unneeded precision over time.</p>

<ul>
<li><strong>g1 (Leibniz/Euler)</strong><br>
An extra variable <code>j</code> is kept, representing <code>2*i+1</code>. The author does the same in the reference implementation. Calculating <code>n</code> separately is far simpler (and less obscure), because it uses the current values of <code>q</code>, <code>r</code> and <code>t</code>, rather than the next.</li>
<li><strong>g2 (Lambert)</strong><br>
The check <code>n == q/s</code> is admittedly quite lax. That should read <code>n == (q*(k+2*j+4)+r)/(s*(k+2*j+4)+t)</code>, where <code>j</code> is <code>2*i-1</code> and <code>k</code> is <code>i*i</code>. At higher iterations, the <code>r</code> and <code>t</code> terms become increasingly less significant. As is, it's good for the first 100,000 digits, so it's probably good for all. The author provides no reference implementation.</li>
<li><strong>g3 (Gosper)</strong><br>
The author conjectures that it is unnecessary to check that <code>n</code> will not change in subsequent iterations, and that it only serves to slow the algorithm. While probably true, the generator is holding onto ~13% more correct digits than it has currently generated, which seems somewhat wasteful. I've added the check back in, and wait until 50 digits are correct, generating them all at once, with a noticable gain in performance.</li>
<li><strong>g4 (Ramanujan 39)</strong><br>
Calculated as<br>
<img src="https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=%7B3528%7D%5Cmiddle%2F%7B%5Csum%5Climits_%7B_%7Bn%3D0%7D%7D%5E%7B_%7B%5Cinfty%7D%7D%7B%5Cfrac%7B%28-1%29%5En+%284n%29%21+%281123%2B21460n%29%7D%7B%28n%21%29%5E4+14112%5E%7B2n%7D%7D%7D%7D" alt=""><br>
Unfortunately, <code>s</code> doesn't zero out, due to the initial (3528 ÷) composition, but it's still significantly faster than g3. Convergence is ~5.89 digits per term, 3511 digits are generated at a time. If that's a bit much, generating 271 digits per 46 iterations is also a decent choice.</li>
</ul>

<p><strong>Timings</strong></p>

<p>Taken on my system, for purposes of comparison only. Times are listed in seconds. If a timing took longer than 10 minutes, I didn't run any further tests.</p>

<pre class="lang-python prettyprint-override"><code>            |  g1_ref |  g1_md  |  g2_md  |  g3_ref |  g3_md  |  g4_md
------------+---------+---------+---------+---------+---------+--------
    10,000  |  1.645  |  0.229  |  0.093  |  0.312  |  0.062  |  0.062
    20,000  |  6.859  |  0.937  |  0.234  |  1.140  |  0.250  |  0.109
    50,000  |  55.62  |  5.546  |  1.437  |  9.703  |  1.468  |  0.234
   100,000  |  247.9  |  24.42  |  5.812  |  39.32  |  5.765  |  0.593
   200,000  |  2,158  |  158.7  |  25.73  |  174.5  |  33.62  |  2.156
   500,000  |    -    |  1,270  |  215.5  |  3,173  |  874.8  |  13.51
 1,000,000  |    -    |    -    |  1,019  |    -    |    -    |  58.02
</code>```

It's interesting that g2 eventually overtakes g3, despite a slower rate of convergence. I suspect this is because the operands grow at a significantly slower rate, winning out in the long run. The fastest implmentation g4_md is approximately 235x faster than the g3_ref implmentation on 500,000 digits. That said, there's still a significant overhead to streaming digits in this way. Calculating all digits directly using Ramanujan 39 (python source) is approximately 10x as fast.

Why not Chudnovsky?

The Chudnovsky algorithm requires a full precision square root, which I'm honestly not sure how to work in - assuming it could be at all. Ramanujan 39 is somewhat special in this regard. However, the method does seem like it might be conducive to Machin-like formulas, such as those used by y-cruncher, so that might be an avenue worth exploring.

Title: Runs of Digits in Pi

Body:
Python 2, 110 bytes

n=input()
x=p=7*n|1
while~-p:x=p/2*x/p+2*10**n;p-=2
l=m=0
for c in`x`:
 l=l*(p==c)+1;p=c
 if l>m:m=l;print p*l

The maximum number of digits to check is taken as from stdin. 10,000 digits finishes in about 2s with PyPy 5.3.

Sample Usage

$ echo 10000 | pypy pi-runs.py
3
33
111
9999
99999
999999

Something Useful

from sys import argv
from gmpy2 import mpz

def pibs(a, b):
  if a == b:
    if a == 0:
      return (1, 1, 1123)
    p = a*(a*(32*a-48)+22)-3
    q = a*a*a*24893568
    t = 21460*a+1123
    return (p, -q, p*t)
  m = (a+b) >> 1
  p1, q1, t1 = pibs(a, m)
  p2, q2, t2 = pibs(m+1, b)
  return (p1*p2, q1*q2, q2*t1 + p1*t2)

if __name__ == '__main__':
  from sys import argv
  digits = int(argv[1])

  pi_terms = mpz(digits*0.16975227728583067)
  p, q, t = pibs(0, pi_terms)

  z = mpz(10)**digits
  pi = 3528*q*z/t

  l=m=0
  x=0
  for c in str(pi):
   l=l*(p==c)+1;p=c
   if l>m:m=l;print x,p*l
   x+=1

I've switched from Chudnovsky to Ramanujan 39 for this. Chudnovsky ran out of memory on my system shortly after 100 million digits, but Ramanujan made it all the way to 400 million, in only about 38 minutes. I think this is another case were slower growth rate of terms wins out in the end, at least on a system with limited resources.

Sample Usage

$ python pi-ramanujan39-runs.py 400000000
0 3
25 33
155 111
765 9999
766 99999
767 999999
710106 3333333
22931752 44444444
24658609 777777777
386980421 6666666666

Faster Unbounded Generators

The reference implementation given in the problem description is interesting. It uses an unbounded generator, taken directly from the paper Unbounded Spigot Algorithms for the Digits of Pi. According to the author, the implementations provided are "deliberately obscure", so I decided to make fresh implementations of all three algorithms listed by the author, without deliberate obfuscation. I've also added a fourth, based on Ramanujan #39.

try:
  from gmpy2 import mpz
except:
  mpz = long

def g1_ref():
  # Leibniz/Euler, reference
  q, r, t = mpz(1), mpz(0), mpz(1)
  i, j = 1, 3
  while True:
    n = (q+r)/t
    if n*t > 4*q+r-t:
      yield n
      q, r = 10*q, 10*(r-n*t)
    q, r, t = q*i, (2*q+r)*j, t*j
    i += 1; j += 2

def g1_md():
  # Leibniz/Euler, multi-digit
  q, r, t = mpz(1), mpz(0), mpz(1)
  i, j = 1, 3
  z = mpz(10)**10
  while True:
    n = (q+r)/t
    if n*t > 4*q+r-t:
      for d in digits(n, i>34 and 10 or 1): yield d
      q, r = z*q, z*(r-n*t)
    u, v, x = 1, 0, 1
    for k in range(33):
      u, v, x = u*i, (2*u+v)*j, x*j
      i += 1; j += 2
    q, r, t = q*u, q*v+r*x, t*x

def g2_md():
  # Lambert, multi-digit
  q, r, s, t = mpz(0), mpz(4), mpz(1), mpz(0)
  i, j, k = 1, 1, 1
  z = mpz(10)**49
  while True:
    n = (q+r)/(s+t)
    if n == q/s:
      for d in digits(n, i>65 and 49 or 1): yield d
      q, r = z*(q-n*s), z*(r-n*t)
    u, v, w, x = 1, 0, 0, 1
    for l in range(64):
      u, v, w, x = u*j+v, u*k, w*j+x, w*k
      i += 1; j += 2; k += j
    q, r, s, t = q*u+r*w, q*v+r*x, s*u+t*w, s*v+t*x

def g3_ref():
  # Gosper, reference
  q, r, t = mpz(1), mpz(180), mpz(60)
  i = 2
  while True:
    u, y = i*(i*27+27)+6, (q+r)/t
    yield y
    q, r, t, i = 10*q*i*(2*i-1), 10*u*(q*(5*i-2)+r-y*t), t*u, i+1

def g3_md():
  # Gosper, multi-digit
  q, r, t = mpz(1), mpz(0), mpz(1)
  i, j = 1, 60
  z = mpz(10)**50
  while True:
    n = (q+r)/t
    if n*t > 6*i*q+r-t:
      for d in digits(n, i>38 and 50 or 1): yield d
      q, r = z*q, z*(r-n*t)
    u, v, x = 1, 0, 1
    for k in range(37):
      u, v, x = u*i*(2*i-1), j*(u*(5*i-2)+v), x*j
      i += 1; j += 54*i
    q, r, t = q*u, q*v+r*x, t*x

def g4_md():
  # Ramanujan 39, multi-digit
  q, r, s ,t = mpz(0), mpz(3528), mpz(1), mpz(0)
  i = 1
  z = mpz(10)**3511
  while True:
    n = (q+r)/(s+t)
    if n == (22583*i*q+r)/(22583*i*s+t):
      for d in digits(n, i>597 and 3511 or 1): yield d
      q, r = z*(q-n*s), z*(r-n*t)
    u, v, x = mpz(1), mpz(0), mpz(1)
    for k in range(596):
      c, d, f = i*(i*(i*32-48)+22)-3, 21460*i-20337, -i*i*i*24893568
      u, v, x = u*c, (u*d+v)*f, x*f
      i += 1
    q, r, s, t = q*u, q*v+r*x, s*u, s*v+t*x

def digits(x, n):
  o = []
  for k in range(n):
    x, r = divmod(x, 10)
    o.append(r)
  return reversed(o)

Notes

Above are 6 implementations: the two reference implementations provided by the author (denoted _ref), and four that compute terms in batches, generating multiple digits at once (_md). All implementations have been confirmed to 100,000 digits. When choosing batch sizes, I chose values that slowly lose precision over time. For example, g1_md generates 10 digits per batch, with 33 iterations. However, this will only produce ~9.93 correct digits. When precision runs out the check condition will fail, triggering an extra batch to be run. This seems to be more performant than slowly gainly extra, unneeded precision over time.

g1 (Leibniz/Euler)

An extra variable j is kept, representing 2*i+1. The author does the same in the reference implementation. Calculating n separately is far simpler (and less obscure), because it uses the current values of q, r and t, rather than the next.

g2 (Lambert)

The check n == q/s is admittedly quite lax. That should read n == (q*(k+2*j+4)+r)/(s*(k+2*j+4)+t), where j is 2*i-1 and k is i*i. At higher iterations, the r and t terms become increasingly less significant. As is, it's good for the first 100,000 digits, so it's probably good for all. The author provides no reference implementation.

g3 (Gosper)

The author conjectures that it is unnecessary to check that n will not change in subsequent iterations, and that it only serves to slow the algorithm. While probably true, the generator is holding onto ~13% more correct digits than it has currently generated, which seems somewhat wasteful. I've added the check back in, and wait until 50 digits are correct, generating them all at once, with a noticable gain in performance.

g4 (Ramanujan 39)

Calculated as

Unfortunately, s doesn't zero out, due to the initial (3528 ÷) composition, but it's still significantly faster than g3. Convergence is ~5.89 digits per term, 3511 digits are generated at a time. If that's a bit much, generating 271 digits per 46 iterations is also a decent choice.

Timings

Taken on my system, for purposes of comparison only. Times are listed in seconds. If a timing took longer than 10 minutes, I didn't run any further tests.

            |  g1_ref |  g1_md  |  g2_md  |  g3_ref |  g3_md  |  g4_md
------------+---------+---------+---------+---------+---------+--------
    10,000  |  1.645  |  0.229  |  0.093  |  0.312  |  0.062  |  0.062
    20,000  |  6.859  |  0.937  |  0.234  |  1.140  |  0.250  |  0.109
    50,000  |  55.62  |  5.546  |  1.437  |  9.703  |  1.468  |  0.234
   100,000  |  247.9  |  24.42  |  5.812  |  39.32  |  5.765  |  0.593
   200,000  |  2,158  |  158.7  |  25.73  |  174.5  |  33.62  |  2.156
   500,000  |    -    |  1,270  |  215.5  |  3,173  |  874.8  |  13.51
 1,000,000  |    -    |    -    |  1,019  |    -    |    -    |  58.02

It's interesting that g2 eventually overtakes g3, despite a slower rate of convergence. I suspect this is because the operands grow at a significantly slower rate, winning out in the long run. The fastest implmentation g4_md is approximately 235x faster than the g3_ref implmentation on 500,000 digits. That said, there's still a significant overhead to streaming digits in this way. Calculating all digits directly using Ramanujan 39 (python source) is approximately 10x as fast.

Why not Chudnovsky?

The Chudnovsky algorithm requires a full precision square root, which I'm honestly not sure how to work in - assuming it could be at all. Ramanujan 39 is somewhat special in this regard. However, the method does seem like it might be conducive to Machin-like formulas, such as those used by y-cruncher, so that might be an avenue worth exploring.


问:
How to determine if a number is odd or even without mod -or- bitwise operations?
How to determine if a number is odd or even without mod -or- bitwise operations?

This challenge is grossly inefficient, but challenges your ability to think outside the box for a creative solution.

EDIT:

Please create a function. Also, while regex is a fun response, the function should accept any valid number.

BACKGROUND:
This question stems from my earliest programming days.  The homework for our first day of class was to write a simple program that printed 'odd' or 'even'.  Being the brat I was, I didn't read the book we had for the class where it simply showed us how to use % to determine that.  I spent about a half hour pacing back in forth in my room trying to think of a way to do this and had remembered from the lecture that numbers can lose and gain precision as they are cast from one primitive type to another.  Therefore, if you took the number, divided it by two and then multiplied it back didn't equal the original number, then you would know that the number was odd.

I was stunned the next day, while our instructor was evaluating our programs, that he thought that it was the most original, if inefficient, way of solving the problem.

答:
Mathematica

Edit:
This is the unimaginative check that many folks, including me, use. If an integer ends in 0,2,4, 6,or 8, it is even, otherwise odd.

```<code>f[n_?IntegerQ] := Print[n, " is ",
If[MemberQ[{0, 2, 4, 6, 8}, IntegerDigits[n][[-1]]], "even.", "odd."]]
</code>```

Original solution:

The following is even more unimaginative and uselessly slow  for "large" integers, but in principle, it works.

If an integer has 2 is its lowest prime factor, it is even.

```<code>f[n_?IntegerQ]:= Print[n, " is ", If[FactorInteger[n][[1, 1]] == 2, "Even", "Odd"]
</code>```

Body:
Mathematica

Edit:
This is the unimaginative check that many folks, including me, use. If an integer ends in 0,2,4, 6,or 8, it is even, otherwise odd.

f[n_?IntegerQ] := Print[n, " is ",
If[MemberQ[{0, 2, 4, 6, 8}, IntegerDigits[n][[-1]]], "even.", "odd."]]

Original solution:

The following is even more unimaginative and uselessly slow  for "large" integers, but in principle, it works.

If an integer has 2 is its lowest prime factor, it is even.

f[n_?IntegerQ]:= Print[n, " is ", If[FactorInteger[n][[1, 1]] == 2, "Even", "Odd"]


问:
Convert n strings of m length to m strings of n length
Write a program that, given any 'n' number of strings of 'm' length, returns 'm' number of 'n'-length strings, with this condition:

Every new string should contains the letters at the same index of the others strings

For example, the first output string must contain the first letter of all the input strings, the second output string must contain the second letter of all the input strings, and so on.

Examples (the numbers under the letters are the indexes of the strings):

```<code>input: "car", "dog", "man", "yay"
        012    012    012    012
output: "cdmy", "aoaa", "rgny"
         0000    1111    2222

input: "money", "taken", "trust"
        01234    01234    01234
output: "mtt", "oar", "nku", "ees", "ynt"
         000    111    222    333    444
</code>```

Assume that the input is correct everytime

Shortest bytes' code wins!

Edit:

Since there are many programming languages, and there could be many possible solutions for each of them, I will post the shortest solution for each programming language and the user who provided it. Keep coding!

Re-Edit:

Thanks to user Dennis I inserted a snippet for the leaderboards.

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
PHP, 82 bytes

```<code>function f($a){foreach($a as$s)foreach(str_split($s)as$i=>$c)$y[$i].=$c;return$y;}
</code>```

takes and returns an array of strings

break down

```<code>function f($a)
{
    foreach($a as$s)                    // loop through array $a
        foreach(str_split($s)as$i=>$c)  // split string to array, loop through characters
            $y[$i].=$c;                 // append character to $i-th result string
    return$y;
}
</code>```

examples

```<code>$samples=[
    ["asd","dsa"], ["ad","ss","da"],
    ["car", "dog", "man", "yay"], ["cdmy", "aoaa", "rgny"],
    ["money", "taken", "trust"], ["mtt", "oar", "nku", "ees", "ynt"]
];
echo '```';
while ($samples)
{
    echo 'in: ';         print_r($x=array_shift($samples));
    echo 'out: ';        print_r(f($x));
    echo 'expected: ';   print_r(array_shift($samples));
    echo '
';
}
```

Body:
PHP, 82 bytes

function f($a){foreach($a as$s)foreach(str_split($s)as$i=>$c)$y[$i].=$c;return$y;}

takes and returns an array of strings

break down

function f($a)
{
    foreach($a as$s)                    // loop through array $a
        foreach(str_split($s)as$i=>$c)  // split string to array, loop through characters
            $y[$i].=$c;                 // append character to $i-th result string
    return$y;
}

examples

$samples=[
    ["asd","dsa"], ["ad","ss","da"],
    ["car", "dog", "man", "yay"], ["cdmy", "aoaa", "rgny"],
    ["money", "taken", "trust"], ["mtt", "oar", "nku", "ees", "ynt"]
];
echo '<pre>';
while ($samples)
{
    echo '<b>in:</b> ';         print_r($x=array_shift($samples));
    echo '<b>out:</b> ';        print_r(f($x));
    echo '<b>expected:</b> ';   print_r(array_shift($samples));
    echo '<hr>';
}


答:
Haskell, 231 bytes

```<code>import Data.List
g(q,r,t,k,n,l)|4*q+r-t<n*t=n:g(10*q,10*(r-n*t),t,k,div(10*(3*q+r))t-10*n,l)|0<1=g(q*k,(2*q+r)*l,t*l,k+1,div(q*(7*k+2)+r*l)(t*l),l+2)
p=nubBy(\x y->length x==length y).concatMap inits.group$g(1,0,1,1,3,3)
</code>```

This uses the Unbounded Spigot Algorithms for the Digits of Pi by Jeremy Gibbons, 2004. The result is p. Technically, it should support infinite output sequences, but that may take a while (and is bounded by your memory).

Title: Runs of Digits in Pi

Body:
Your goal is to output the strictly increasing sequence of consecutive, identical digits of pi (π). Each term in the sequence must be one digit longer than the previous. So 3 (0th digit of pi) is the first time a run of digits occurs (length 1). The next to occur is 33 (digits 24 and 25 of pi). Of course, this sequence requires the digits of pi to be in base 10.

The ones known so far, and the first six all occur within the first 800 digits:

```<code>3
33
111
9999
99999
999999
3333333
44444444
777777777
6666666666
... (not in first 2 billion digits)
</code>```

Note that the consecutive nines all occur together, in the same run, so if the next larger run you found happened to be 1000 consecutive 0s, this would fill in multiple terms of the sequence.

I have not found any more terms with my program. I know there are no more terms within the first 50000 digits or more. My program was taking too long with 500000 digits, so I gave up.

Reference Implementation

You may:

Output the sequence forever

Take an integer n and find the first n numbers in the sequence

Take an integer n and find the numbers in the sequence contained in the first n digits of pi.

Make sure to specify which one your code does. The number n may be zero or one indexed.

Inspired by this mathoverflow question.

Body:
Haskell, 231 bytes

import Data.List
g(q,r,t,k,n,l)|4*q+r-t<n*t=n:g(10*q,10*(r-n*t),t,k,div(10*(3*q+r))t-10*n,l)|0<1=g(q*k,(2*q+r)*l,t*l,k+1,div(q*(7*k+2)+r*l)(t*l),l+2)
p=nubBy(\x y->length x==length y).concatMap inits.group$g(1,0,1,1,3,3)

This uses the Unbounded Spigot Algorithms for the Digits of Pi by Jeremy Gibbons, 2004. The result is p. Technically, it should support infinite output sequences, but that may take a while (and is bounded by your memory).


问:
Calculate A190810
Your task is pretty simple, calculate the n-th element of A190810.

Elements of A190810 are calculated according to these rules:

The first element is 1

The sequence is increasing

If x occurs in the sequence, then 2x+1 and 3x-1 also do

You can use 1-based or 0-based indexing, but if you use 0-based indexing, please say it in the answer.

Test cases

```<code>a(1) = 1
a(2) = 2
a(3) = 3
a(4) = 5
a(5) = 7
a(10) = 17
a(20) = 50
a(30) = 95
a(55) = 255
</code>```

Since this is code-golf, the shortest answer in bytes wins!

答:
Jelly, 16 bytes

```<code>×3’;Ḥ‘$;
1Ç¡ṢQ³ị
</code>```

Very inefficient. Try it online!

How it works

```<code>1Ç¡ṢQ³ị   Main link. Argument: n (integer)

1         Set the return value to 1.
 Ç¡       Execute the helper link n times.
   Ṣ      Sort the resulting array.
    Q     Unique; deduplicate the sorted array.
     ³ị   Retrieve its n-th element.

×3’;Ḥ‘$;  Helper link. Argument: A (array)

×3        Multiply all elements of A by 3.
  ’       Decrement the resulting products.
      $   Combine the two links to the left into a monadic chain.
    Ḥ     Unhalve; multiply all elements of A by 2.
     ‘    Increment the resulting products.
   ;      Concatenate 3A-1 and 2A+1.
       ;  Concatenate the result with A.
</code>```

Title: Calculate A190810

Body:
Jelly, 16 bytes

×3’;Ḥ‘$;
1Ç¡ṢQ³ị

Very inefficient. Try it online!

How it works

1Ç¡ṢQ³ị   Main link. Argument: n (integer)

1         Set the return value to 1.
 Ç¡       Execute the helper link n times.
   Ṣ      Sort the resulting array.
    Q     Unique; deduplicate the sorted array.
     ³ị   Retrieve its n-th element.

×3’;Ḥ‘$;  Helper link. Argument: A (array)

×3        Multiply all elements of A by 3.
  ’       Decrement the resulting products.
      $   Combine the two links to the left into a monadic chain.
    Ḥ     Unhalve; multiply all elements of A by 2.
     ‘    Increment the resulting products.
   ;      Concatenate 3A-1 and 2A+1.
       ;  Concatenate the result with A.


答:
Python 2, <s>88</s> <s>83</s> 72 bytes

You may want to read the programs in this answer in reverse order...

Slower and shorter still, thanks to Dennis:

L=1,;exec'L+=2*L[0]+1,3*L[0]-1;L=sorted(set(L))[1:];'*input()
print L[0]
```
<p><strong>Try it online</strong></p>
<hr />
<p>This doesn't run as fast, but is shorter (<strong>83 bytes</strong>.) By sorting and removing duplicates each iteration, as well as removing the first element, I remove the need for an index into the list. The result is simply the first element after <code>n</code> iterations.</p>
<p>I may have out-golfed Dennis. :D</p>
<pre class="lang-python prettyprint-override"><code>L=[1]
n=input()
while n:L+=[2*L[0]+1,3*L[0]-1];n-=1;L=sorted(set(L))[1:]
print L[0]
</code>```

Try it online

This version below (88 bytes) runs really fast, finding the 500000th element in about two seconds.

It's pretty simple. Compute elements of the list until there are three times more elements than n, since every element added may add at most 2 more unique elements. Then remove duplicates, sort, and print the nth element (zero-indexed.)

L=[1]
i=0
n=input()
while len(L)<3*n:L+=[2*L[i]+1,3*L[i]-1];i+=1
print sorted(set(L))[n]
```

Try it online

Title: Calculate A190810

Body:
Your task is pretty simple, calculate the n-th element of A190810.

Elements of A190810 are calculated according to these rules:

The first element is 1

The sequence is increasing

If x occurs in the sequence, then 2x+1 and 3x-1 also do

You can use 1-based or 0-based indexing, but if you use 0-based indexing, please say it in the answer.

Test cases

```<code>a(1) = 1
a(2) = 2
a(3) = 3
a(4) = 5
a(5) = 7
a(10) = 17
a(20) = 50
a(30) = 95
a(55) = 255
</code>```

Since this is code-golf, the shortest answer in bytes wins!

Body:
Python 2, <s>88</s> <s>83</s> 72 bytes

You may want to read the programs in this answer in reverse order...

Slower and shorter still, thanks to Dennis:

L=1,;exec'L+=2*L[0]+1,3*L[0]-1;L=sorted(set(L))[1:];'*input()
print L[0]

Try it online

This doesn't run as fast, but is shorter (83 bytes.) By sorting and removing duplicates each iteration, as well as removing the first element, I remove the need for an index into the list. The result is simply the first element after n iterations.

I may have out-golfed Dennis. :D

L=[1]
n=input()
while n:L+=[2*L[0]+1,3*L[0]-1];n-=1;L=sorted(set(L))[1:]
print L[0]

Try it online

This version below (88 bytes) runs really fast, finding the 500000th element in about two seconds.

It's pretty simple. Compute elements of the list until there are three times more elements than n, since every element added may add at most 2 more unique elements. Then remove duplicates, sort, and print the nth element (zero-indexed.)

L=[1]
i=0
n=input()
while len(L)<3*n:L+=[2*L[i]+1,3*L[i]-1];i+=1
print sorted(set(L))[n]

Try it online


答:
Pyth, <s>20</s> 19 bytes

```<code>hutS{+G,hyhGt*3hGQ0
</code>```

Try it online. Test suite.

Uses zero-based indexing.

Title: Calculate A190810

Body:
Pyth, <s>20</s> 19 bytes

hutS{+G,hyhGt*3hGQ0

Try it online. Test suite.

Uses zero-based indexing.


答:
Python 2, <s>88</s> 84 bytes

g=lambda k:g(k%2*k/2)|g(k%3/2*-~k/3)if k>1else k
f=lambda n,k=1:n and-~f(n-g(k),k+1)
```

Test it on Ideone.

Title: Calculate A190810

Body:
Python 2, <s>88</s> 84 bytes

g=lambda k:g(k%2*k/2)|g(k%3/2*-~k/3)if k>1else k
f=lambda n,k=1:n and-~f(n-g(k),k+1)

Test it on Ideone.


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

```<code>1w:"tEQy3*qvSu]G)
</code>```

This is an extremely inefficient algorithm. The online interpreter runs out of memory for inputs greater than 13.

One byte saved, thanks to Luis Mendo!

Try it online!

This version is longer, but more efficient (21 bytes)

```<code>1`tEQy3*qvSutnG3*<]G)
</code>```

Try it online

Explanation:

The logical way to do it, is to add elements to the array until it is long enough to grab the i'th element. That's how the efficient one works. The golfy (and inefficient) way to do it, is to just increase the array size i times.

So first, we define the start array: 1. Then we swap the top two elements, so that input is on top. w. Now, we loop through the input with :". So i times:

```<code>t             %Duplicate our starting (or current) array.
 EQ           %Double it and increment
   y          %Push our starting array again
    3*q       %Multiply by 3 and decrement
       v      %Concatenate these two arrays and the starting array
        Su    %Sort them and remove all duplicate elements.
</code>```

Now, we have a gigantic array of the sequence. (Way more than is needed to calculate) So we stop looping, ], and grab the i'th number from this array with G) (1-indexed)

Title: Calculate A190810

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

1w:"tEQy3*qvSu]G)

This is an extremely inefficient algorithm. The online interpreter runs out of memory for inputs greater than 13.

One byte saved, thanks to Luis Mendo!

Try it online!

This version is longer, but more efficient (21 bytes)

1`tEQy3*qvSutnG3*<]G)

Try it online

Explanation:

The logical way to do it, is to add elements to the array until it is long enough to grab the i'th element. That's how the efficient one works. The golfy (and inefficient) way to do it, is to just increase the array size i times.

So first, we define the start array: 1. Then we swap the top two elements, so that input is on top. w. Now, we loop through the input with :". So i times:

t             %Duplicate our starting (or current) array.
 EQ           %Double it and increment
   y          %Push our starting array again
    3*q       %Multiply by 3 and decrement
       v      %Concatenate these two arrays and the starting array
        Su    %Sort them and remove all duplicate elements.

Now, we have a gigantic array of the sequence. (Way more than is needed to calculate) So we stop looping, ], and grab the i'th number from this array with G) (1-indexed)


答:
Haskell, 77 74 bytes

```<code>import Data.List
i=insert
f(x:y)=x:f(i(2*x+1)$i(3*x-1)y)
a=(!!)(nub$f[1])
</code>```

This provides a function a for the n-th entry. It's zero indexed. Alternatively, a=nub$f[1] will create the whole list (lazily).

It's a list-variant of Reinhard Zumkeller's Set code.

Title: Calculate A190810

Body:
Haskell, 77 74 bytes

import Data.List
i=insert
f(x:y)=x:f(i(2*x+1)$i(3*x-1)y)
a=(!!)(nub$f[1])

This provides a function a for the n-th entry. It's zero indexed. Alternatively, a=nub$f[1] will create the whole list (lazily).

It's a list-variant of Reinhard Zumkeller's Set code.


问:
m3ph1st0s's programming puzzle 1 (C++)
This is the first of a series of C++ puzzles for you. Hope you will enjoy.

So, puzzle no.1:

Given the following program:

```<code>#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}
</code>```

Insert some code on a single new line anywhere inside the program so that the output will be 0. The new line will contain AT MOST 18 characters (including spaces), and the rest of the lines will remain unmodified.
 To be clear, here is an example of a valid new code:

```<code>#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   int* p = NULL;
   const float c=0.5;
   std::cout << a/b-a*c;
}
</code>```

A new line with 15 characters was inserted so it's ok. However it does not solve the problem.

If this is too simple for you, don't worry, more is coming!!

答:
```<code>#include <iostream>
int main()
{
int a;if(a)
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}
</code>```

How about these 11 chars...

Title: m3ph1st0s's programming puzzle 1 (C++)

Body:
#include <iostream>
int main()
{
int a;if(a)
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}

How about these 11 chars...


问:
Draw the national flag of Iceland
This year's UEFA Euro 2016 is over and besides a couple of negative headlines there has been a very positive surprise as well – the Iceland national football team. Let's draw their national flag.

Input

Well, obviously this challenge has no input.

Output

Draw the flag of Iceland in any applicable visual format of at least 100 x 72 pixels or 25 x 18 characters.

Save the output to a file or present it instantly – example formats are: images like png, jpg etc., vector graphics, draw on HTML canvas or even use non-whitespace characters for visualization.

Use these colors: blue: #0048e0, white: #ffffff and red: #d72828.

If your language doesn't support specific color values, use the standard values for red, blue and white from the ANSI color codes.

Draw the flag with the correct proportions, as shown in the figure below:

Boilerplate

You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it.

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

Standard loopholes are disallowed.

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

If you can't find your answer, format your language and byte count as explained in the Leaderboard's "Info Section".

This challenge is inspired by Draw the national flag of france.

答:
R/ggplot2, <s>273 bytes</s> 270 bytes

Since we have a couple base R answers we obviously need a ggplot answer. One of the few areas where base might be better ;)

```<code>library(ggplot2);ggplot(data.frame(a=c(0,7,0,8,0),b=c(25,11,25,10,25),c=c(0,0,7,0,8),d=c(18,18,11,18,10),e=paste(c(1,2,2,3,3))),aes(xmin=a,xmax=b,ymin=c,ymax=d,fill=e))+geom_rect()+scale_fill_manual(values=c('#0048e0','white','#d72828'),g=F)+theme_void();ggsave('o.png')
</code>```

Output

Ungolfed

```<code>library(ggplot2)

ggplot(
  data.frame(xmin = c(0,  7,  0,  8,  0),
             xmax = c(25, 11, 25, 10, 25),
             ymin = c(0,  0,  7,  0,  8),
             ymax = c(18, 18, 11, 18, 10),
             fill = paste(c(1, 2, 2, 3, 3)))
) +
aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = fill)+
geom_rect() +
scale_fill_manual(values = c('#0048e0', 'white', '#d72828'), g = FALSE) +
theme_void()

ggsave('o.png')
</code>```

Edit: Thanks to plannapus for suggesting a way to shorten the fill specification.

Title: Draw the national flag of Iceland

Body:
R/ggplot2, <s>273 bytes</s> 270 bytes

Since we have a couple base R answers we obviously need a ggplot answer. One of the few areas where base might be better ;)

library(ggplot2);ggplot(data.frame(a=c(0,7,0,8,0),b=c(25,11,25,10,25),c=c(0,0,7,0,8),d=c(18,18,11,18,10),e=paste(c(1,2,2,3,3))),aes(xmin=a,xmax=b,ymin=c,ymax=d,fill=e))+geom_rect()+scale_fill_manual(values=c('#0048e0','white','#d72828'),g=F)+theme_void();ggsave('o.png')

Output

Ungolfed

library(ggplot2)

ggplot(
  data.frame(xmin = c(0,  7,  0,  8,  0),
             xmax = c(25, 11, 25, 10, 25),
             ymin = c(0,  0,  7,  0,  8),
             ymax = c(18, 18, 11, 18, 10),
             fill = paste(c(1, 2, 2, 3, 3)))
) +
aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = fill)+
geom_rect() +
scale_fill_manual(values = c('#0048e0', 'white', '#d72828'), g = FALSE) +
theme_void()

ggsave('o.png')

Edit: Thanks to plannapus for suggesting a way to shorten the fill specification.


答:
Brachylog, 45 bytes

```<code>:1-I,?:?*:1ydo:Im.
1.|:1-:1&I(:3*:1-.;I*:1+.)
</code>```

Computes N = 1000 in about 6 seconds on my machine.

This is 1-indexed, e.g.

```<code>run_from_file('code.brachylog',1000,Z).
Z = 13961 .
</code>```

Explanation

Main predicate:

```<code>:1-I,               I = Input - 1
     ?:?*           Square the Input
         :1y        Find the first Input*Input valid outputs of predicate 1
            do      Remove duplicates and order
              :Im.  Output is the Ith element
</code>```

Predicate 1:

```<code>1.                  Input = Output = 1
|                   Or
:1-:1&I             I is the output of predicate 1 called with Input - 1 as input
       (
         :3*:1-.      Output is 3*I-1
       ;            Or
         I*:1+.       Output is 2*I+1
       )
</code>```

You may note that we don't pass any input to predicate 1 when we call y - Yield. Because of constraint propagation, it will find the right input once reaching the 1. clause which will propagate the correct input values.

Title: Calculate A190810

Body:
Brachylog, 45 bytes

:1-I,?:?*:1ydo:Im.
1.|:1-:1&I(:3*:1-.;I*:1+.)

Computes N = 1000 in about 6 seconds on my machine.

This is 1-indexed, e.g.

run_from_file('code.brachylog',1000,Z).
Z = 13961 .

Explanation

Main predicate:

:1-I,               I = Input - 1
     ?:?*           Square the Input
         :1y        Find the first Input*Input valid outputs of predicate 1
            do      Remove duplicates and order
              :Im.  Output is the Ith element

Predicate 1:

1.                  Input = Output = 1
|                   Or
:1-:1&I             I is the output of predicate 1 called with Input - 1 as input
       (
         :3*:1-.      Output is 3*I-1
       ;            Or
         I*:1+.       Output is 2*I+1
       )

You may note that we don't pass any input to predicate 1 when we call y - Yield. Because of constraint propagation, it will find the right input once reaching the 1. clause which will propagate the correct input values.


答:
05AB1E, <s>18</s> 17 bytes

Uses CP-1252 encoding.

```<code>$FÐ·>s3*<)˜Ù}ï{¹è
</code>```

Explanation

```<code>$                  # initialize with 1
 F          }      # input number of times do
  Ð                # triplicate current list/number
   ·>              # double one copy and add 1
     s3*<          # multiply one copy by 3 and subtract 1
         )˜Ù       # combine the 3 lists to 1 list and remove duplicates
             ï{    # convert list to int and sort
               ¹è  # take the element from the list at index input
</code>```

Try it online for small numbers

Very slow.

Uses 0-based indexing.

Title: Calculate A190810

Body:
05AB1E, <s>18</s> 17 bytes

Uses CP-1252 encoding.

$FÐ·>s3*<)˜Ù}ï{¹è

Explanation

$                  # initialize with 1
 F          }      # input number of times do
  Ð                # triplicate current list/number
   ·>              # double one copy and add 1
     s3*<          # multiply one copy by 3 and subtract 1
         )˜Ù       # combine the 3 lists to 1 list and remove duplicates
             ï{    # convert list to int and sort
               ¹è  # take the element from the list at index input

Try it online for small numbers

Very slow.

Uses 0-based indexing.


答:
Python 2, 59 bytes

t={1}
exec'm=min(t);t=t-{m}|{2*m+1,3*m-1};'*input()
print m
```

Based on @mbomb007's Python answer. Test it on Ideone.

Title: Calculate A190810

Body:
Python 2, 59 bytes

t={1}
exec'm=min(t);t=t-{m}|{2*m+1,3*m-1};'*input()
print m

Based on @mbomb007's Python answer. Test it on Ideone.


答:
J, 14 bytes

```<code>+/@(*|.)&(/:~)
</code>```

Uses the same principle as the others.

Explanation

```<code>+/@(*|.)&(/:~)  Input: x on LHS and y on RHS
        &(/:~)  Sort both x and y
     |.         Reverse the sorted y
    *           Multiply the sorted x and reversed sorted y elementwise
+/@             Reduce the products using addition and return
</code>```

Title: Minimum Scalar Product

Body:
Minimum Scalar Product

The inspiration for this code golf problem is from Google's code jam competition. The premise behind the problem is, given the input of two vectors of varying lengths, find the minimum possible scalar. A scalar can be found using the following formula:

```<code>x1 * y1 + x2 * y2 + ... + xn * yn
</code>```

The problem, however, is that multiple values for the scalar can be found depending on the order of the numerals in the input case (seen below). Your goal is to determine the minimum possible scalar integer solution by plugging in the input case numbers into the equation and solving for it. You may use every number in the input only once, and must use all of the numbers.

Allow me to provide an example with the following vectors.

Input

```<code>3
1 3 -5
-2 4 1
</code>```

Output

```<code>-25
</code>```

The first integer on the line represents the number of numbers, n, in each vector. In this case, we have three numbers in each vector.

The number n may vary with each test case, but there will always be two vectors.

In the example input, the minimum scalar product would be -25.

```<code>(-5 * 4) + (1 * 1) + (3 * -2) = 25
</code>```

Rules

You may only use each integer in both vectors once.

You must use all integers in the vectors.

Your output must only include the final product

I'll select the solution with the least amount of code, which follows all of the specifications listed above, in any language!

 Hint: You don't need to brute force this problem, unless it makes your code shorter. There is a specific method involved in finding the minimum spanning scalar :).

Body:
J, 14 bytes

+/@(*|.)&(/:~)

Uses the same principle as the others.

Explanation

+/@(*|.)&(/:~)  Input: x on LHS and y on RHS
        &(/:~)  Sort both x and y
     |.         Reverse the sorted y
    *           Multiply the sorted x and reversed sorted y elementwise
+/@             Reduce the products using addition and return


答:
JavaScript (ES6), 63 bytes

```<code>f=(n,a=[1],i=0)=>a[i++]?--n?f(n,a,a[i*2]=a[i*3-2]=1):i:f(n,a,i)
</code>```

Probably gives up quickly due to the recursion.

Title: Calculate A190810

Body:
JavaScript (ES6), 63 bytes

f=(n,a=[1],i=0)=>a[i++]?--n?f(n,a,a[i*2]=a[i*3-2]=1):i:f(n,a,i)

Probably gives up quickly due to the recursion.

ContentLicense: CC BY-SA 4.0


答:
CJam (25 bytes)

```<code>ri1a1${{_2*)1$3*(}%_&}*$=
</code>```

Online demo. Note that this uses zero-based indexing.

This uses a similar approach to most: apply the transforms n times and then sort and extract the nth item. As a nod to efficiency the deduplication is applied inside the loop and the sorting is applied outside the loop.

Title: Calculate A190810

Body:
CJam (25 bytes)

ri1a1${{_2*)1$3*(}%_&}*$=

Online demo. Note that this uses zero-based indexing.

This uses a similar approach to most: apply the transforms n times and then sort and extract the nth item. As a nod to efficiency the deduplication is applied inside the loop and the sorting is applied outside the loop.


答:
Python 3.5, <s>278</s> 263 bytes:

```<code>import decimal,re;decimal.getcontext().prec=int(input());D=decimal.Decimal;a=p=1;b,t=1/D(2).sqrt(),1/D(4)
for i in[1]*50:z=(a+b)/2;b=(a*b).sqrt();t-=p*(a-z)**2;a=z;p*=2;pi=(z*2)**2/(4*t);i=0;C=lambda r:re.search(r'(\d)\1{%s}'%r,str(pi))
while C(i):print(C(i));i+=1
</code>```

This takes in n as an input for the first n digits of π and then outputs the members of the sequence in those first n digits. Now, this uses Python's built in decimal module to go beyond Python's floating-point limitations, and then sets the precision, or epsilon, to however much the user inputs. Then, to calculate π, this goes through 50 iterations using the efficient Gausse-Legendre algorithm, since the algorithm apparently doubles the number of correct digits each time, and therefore, in 50 iterations, we can get up to 2^50 or 1,125,899,906,842,624 correct digits. Finally, after the calculations are done, it uses a regular expression with string formatting in a while loop to find and print re match objects (which I hope is okay) for all continuous, recurring digits 1 digit longer than in the previous iteration through the loop.

I was able to use this algorithm to successfully and accurately calculate π up to 10,000,000 (ten million) digits, which took about 4 hours and 12 minutes to complete. The following was the final output:

```<code><_sre.SRE_Match object; span=(0, 1), match='3'>
<_sre.SRE_Match object; span=(25, 27), match='33'>
<_sre.SRE_Match object; span=(154, 157), match='111'>
<_sre.SRE_Match object; span=(763, 767), match='9999'>
<_sre.SRE_Match object; span=(763, 768), match='99999'>
<_sre.SRE_Match object; span=(763, 769), match='999999'>
<_sre.SRE_Match object; span=(710101, 710108), match='3333333'>
</code>```

So, I can confidently say that the 8th number in the sequence does not even occur within the first 10 million digits! π is one random number...

Title: Runs of Digits in Pi

Body:
Your goal is to output the strictly increasing sequence of consecutive, identical digits of pi (π). Each term in the sequence must be one digit longer than the previous. So 3 (0th digit of pi) is the first time a run of digits occurs (length 1). The next to occur is 33 (digits 24 and 25 of pi). Of course, this sequence requires the digits of pi to be in base 10.

The ones known so far, and the first six all occur within the first 800 digits:

```<code>3
33
111
9999
99999
999999
3333333
44444444
777777777
6666666666
... (not in first 2 billion digits)
</code>```

Note that the consecutive nines all occur together, in the same run, so if the next larger run you found happened to be 1000 consecutive 0s, this would fill in multiple terms of the sequence.

I have not found any more terms with my program. I know there are no more terms within the first 50000 digits or more. My program was taking too long with 500000 digits, so I gave up.

Reference Implementation

You may:

Output the sequence forever

Take an integer n and find the first n numbers in the sequence

Take an integer n and find the numbers in the sequence contained in the first n digits of pi.

Make sure to specify which one your code does. The number n may be zero or one indexed.

Inspired by this mathoverflow question.

Body:
Python 3.5, <s>278</s> 263 bytes:

import decimal,re;decimal.getcontext().prec=int(input());D=decimal.Decimal;a=p=1;b,t=1/D(2).sqrt(),1/D(4)
for i in[1]*50:z=(a+b)/2;b=(a*b).sqrt();t-=p*(a-z)**2;a=z;p*=2;pi=(z*2)**2/(4*t);i=0;C=lambda r:re.search(r'(\d)\1{%s}'%r,str(pi))
while C(i):print(C(i));i+=1

This takes in n as an input for the first n digits of π and then outputs the members of the sequence in those first n digits. Now, this uses Python's built in decimal module to go beyond Python's floating-point limitations, and then sets the precision, or epsilon, to however much the user inputs. Then, to calculate π, this goes through 50 iterations using the efficient Gausse-Legendre algorithm, since the algorithm apparently doubles the number of correct digits each time, and therefore, in 50 iterations, we can get up to 2^50 or 1,125,899,906,842,624 correct digits. Finally, after the calculations are done, it uses a regular expression with string formatting in a while loop to find and print re match objects (which I hope is okay) for all continuous, recurring digits 1 digit longer than in the previous iteration through the loop.

I was able to use this algorithm to successfully and accurately calculate π up to 10,000,000 (ten million) digits, which took about 4 hours and 12 minutes to complete. The following was the final output:

<_sre.SRE_Match object; span=(0, 1), match='3'>
<_sre.SRE_Match object; span=(25, 27), match='33'>
<_sre.SRE_Match object; span=(154, 157), match='111'>
<_sre.SRE_Match object; span=(763, 767), match='9999'>
<_sre.SRE_Match object; span=(763, 768), match='99999'>
<_sre.SRE_Match object; span=(763, 769), match='999999'>
<_sre.SRE_Match object; span=(710101, 710108), match='3333333'>

So, I can confidently say that the 8th number in the sequence does not even occur within the first 10 million digits! π is one random number...


问:
ASCII art reflection
In this challenge, you will be given a text block, and you need to perform reflection on the text.

Input:

A string to be reflected. The text may not be supplied as an array whose elements are the lines of text. For example, "ab\ncd" and ['a','b','\n','c','d'] are allowed, but ['ab','cd'] or [['a','b'],['c','d']] are not. You can assume that all of the lines have the same number of characters (padded with whitespace where needed).

A boolean where True indicates Y reflection and False indicates X reflection

The two inputs can be passed in any order.

Output:

The reflected string. The characters do not change, only their position. The resulting image block should be aligned to the top left (the first row and column must each contain a non-whitespace character). Trailing whitespace (on any of the lines) is allowed.

Test cases:

```<code>False
  o /
--|/
  |
 / \

/ o
 /|--
  |
 \ /
</code>```

```<code>True
  o /
--|/
  |
 / \

 / \
  |
--|/
  o /
</code>```

```<code>True
text

text
</code>```

```<code>False
text

txet
</code>```

```<code>True
P
P
C
G

G
C
P
P
</code>```

```<code>False
P
P
C
G

P
P
C
G
</code>```

```<code>True
abcde
fghij
kl mn
opqrs
tuvwx

tuvwx
opqrs
kl mn
fghij
abcde
</code>```

This is a code-golf, so answer with the shortest answer in your favorite language!

答:
32-bit x86 machine code, 76 bytes

In hex:

```<code>31c031c9495789f7fcf2aef7d15192b00a89f7f2ae5829f7f7f787f95f4b89c3741287d94b534b8a041eaa75f95b01dea4e2f2c348f7e101c6b00a5651f3a4595e29ce4f4b0f44c3aa75f0c3
</code>```

Input: EBX: direction flag (0/1), ESI: input string, EDI: output buffer. Input is required to be rectangular.

```<code>0:  31 c0               xor eax,eax         ;EAX=0
2:  31 c9               xor ecx,ecx
4:  49                  dec ecx             ;ECX=(uint)-1
5:  57                  push edi
6:  89 f7               mov edi,esi
8:  fc                  cld
9:  f2 ae               repne scasb         ;Scan input string for terminating NULL
b:  f7 d1               not ecx             ;ECX==<input string length (including NULL)>
d:  51                  push ecx
e:  92                  xchg edx,eax        ;EDX=0
f:  b0 0a               mov al,0x0a         ;'\n'
11: 89 f7               mov edi,esi
13: f2 ae               repne scasb         ;Scan input string for the first newline
15: 58                  pop eax             ;EAX==<input string length (including NULL)>
16: 29 f7               sub edi,esi         ;EDI==<single line length (including '\n')>
18: f7 f7               div edi             ;EAX==<# of lines>
1a: 87 f9               xchg ecx,edi        ;ECX=EDI
1c: 5f                  pop edi             ;EDI=<dest buffer>
1d: 4b                  dec ebx             ;Test input flag (0/1)
1e: 89 c3               mov ebx,eax         ;EBX=<# of lines>
20: 74 12               je _vertical
22: 87 d9               xchg ecx,ebx        ;Horisontal flip, exchange ECX & EBX so we can use LOOP
24: 4b                  dec ebx             ;EBX=<single line length (excluding '\n')>
_hfouter:
25: 53                  push ebx
_hfinner:
26: 4b                  dec ebx             ;Decrement inner loop counter
27: 8a 04 1e            mov al,[esi+ebx]    ;AL=ESI[EBX]
2a: aa                  stosb               ;*EDI++=AL
2b: 75 f9               jne _hfinner        ;EBX==0 => break
2d: 5b                  pop ebx
2e: 01 de               add esi,ebx         ;*ESI=='\n' (\0 on the last line)
30: a4                  movsb               ;*EDI++=*ESI++, ESI now points to the next line
31: e2 f2               loop _hfouter       ;--ECX==0 => break
33: c3                  ret                 ;Nothing more to do here
_vertical:
34: 48                  dec eax             ;# of strings less one
35: f7 e1               mul ecx             ;Line length (including '\n')
37: 01 c6               add esi,eax         ;ESI+=ECX*(EAX-1), ESI now points to the beginning of the last line
39: b0 0a               mov al,0x0a         ;'\n'
_vfloop:
3b: 56                  push esi
3c: 51                  push ecx
3d: f3 a4               rep movsb           ;Copy the whole line to the output including newline/NULL at the end
3f: 59                  pop ecx
40: 5e                  pop esi
41: 29 ce               sub esi,ecx         ;Set ESI to the beginning of the previous line
43: 4f                  dec edi             ;*EDI=='\n' (0 on the first iteration), should overwrite it with correct value
44: 4b                  dec ebx             ;Decrement loop counter
45: 0f 44 c3            cmove eax,ebx       ;if (EBX==0) EAX=EBX, this clears EAX on the last iteration
48: aa                  stosb               ;*EDI++=EBX?'\n':0
49: 75 f0               jne _vfloop         ;EBX==0 => break
4b: c3                  ret
</code>```

Title: ASCII art reflection

Body:
32-bit x86 machine code, 76 bytes

In hex:

31c031c9495789f7fcf2aef7d15192b00a89f7f2ae5829f7f7f787f95f4b89c3741287d94b534b8a041eaa75f95b01dea4e2f2c348f7e101c6b00a5651f3a4595e29ce4f4b0f44c3aa75f0c3

Input: EBX: direction flag (0/1), ESI: input string, EDI: output buffer. Input is required to be rectangular.

0:  31 c0               xor eax,eax         ;EAX=0
2:  31 c9               xor ecx,ecx
4:  49                  dec ecx             ;ECX=(uint)-1
5:  57                  push edi
6:  89 f7               mov edi,esi
8:  fc                  cld
9:  f2 ae               repne scasb         ;Scan input string for terminating NULL
b:  f7 d1               not ecx             ;ECX==<input string length (including NULL)>
d:  51                  push ecx
e:  92                  xchg edx,eax        ;EDX=0
f:  b0 0a               mov al,0x0a         ;'\n'
11: 89 f7               mov edi,esi
13: f2 ae               repne scasb         ;Scan input string for the first newline
15: 58                  pop eax             ;EAX==<input string length (including NULL)>
16: 29 f7               sub edi,esi         ;EDI==<single line length (including '\n')>
18: f7 f7               div edi             ;EAX==<# of lines>
1a: 87 f9               xchg ecx,edi        ;ECX=EDI
1c: 5f                  pop edi             ;EDI=<dest buffer>
1d: 4b                  dec ebx             ;Test input flag (0/1)
1e: 89 c3               mov ebx,eax         ;EBX=<# of lines>
20: 74 12               je _vertical
22: 87 d9               xchg ecx,ebx        ;Horisontal flip, exchange ECX & EBX so we can use LOOP
24: 4b                  dec ebx             ;EBX=<single line length (excluding '\n')>
_hfouter:
25: 53                  push ebx
_hfinner:
26: 4b                  dec ebx             ;Decrement inner loop counter
27: 8a 04 1e            mov al,[esi+ebx]    ;AL=ESI[EBX]
2a: aa                  stosb               ;*EDI++=AL
2b: 75 f9               jne _hfinner        ;EBX==0 => break
2d: 5b                  pop ebx
2e: 01 de               add esi,ebx         ;*ESI=='\n' (\0 on the last line)
30: a4                  movsb               ;*EDI++=*ESI++, ESI now points to the next line
31: e2 f2               loop _hfouter       ;--ECX==0 => break
33: c3                  ret                 ;Nothing more to do here
_vertical:
34: 48                  dec eax             ;# of strings less one
35: f7 e1               mul ecx             ;Line length (including '\n')
37: 01 c6               add esi,eax         ;ESI+=ECX*(EAX-1), ESI now points to the beginning of the last line
39: b0 0a               mov al,0x0a         ;'\n'
_vfloop:
3b: 56                  push esi
3c: 51                  push ecx
3d: f3 a4               rep movsb           ;Copy the whole line to the output including newline/NULL at the end
3f: 59                  pop ecx
40: 5e                  pop esi
41: 29 ce               sub esi,ecx         ;Set ESI to the beginning of the previous line
43: 4f                  dec edi             ;*EDI=='\n' (0 on the first iteration), should overwrite it with correct value
44: 4b                  dec ebx             ;Decrement loop counter
45: 0f 44 c3            cmove eax,ebx       ;if (EBX==0) EAX=EBX, this clears EAX on the last iteration
48: aa                  stosb               ;*EDI++=EBX?'\n':0
49: 75 f0               jne _vfloop         ;EBX==0 => break
4b: c3                  ret


答:
Common Lisp, 62 bytes

```<code>(lambda(s)(apply'map'list(lambda(&rest x)(coerce x'string))s))
</code>```

The map function takes a result type (here list), a function f to apply and one or more sequences s1, ..., sn. All sequences are iterated in parallel. For each tuple of elements (e1,...,en) taken from those sequences, we call (f e1 ... en) and the result is accumulated in a sequence of the desired type.

We take a list of strings, say ("car" "dog" "man" "yay"), and use apply to call map. We have to do this so that the input list is used as more arguments to map. More precisely, this:

```<code>(apply #'map 'list fn '("car" "dog" "man" "yay"))
</code>```

... is equivalent to:

```<code>(map 'list f "car" "dog" "man" "yay")
</code>```

And since strings are sequences, we iterate in parallel over all first characters, then all second characters, etc... For example, the first iteration calls f as follows:

```<code>(f #\c #\d #\m #\y)
</code>```

The anonymous lambda takes the list of arguments given to it and coerces it back to a string.

Title: Convert n strings of m length to m strings of n length

Body:
Write a program that, given any 'n' number of strings of 'm' length, returns 'm' number of 'n'-length strings, with this condition:

Every new string should contains the letters at the same index of the others strings

For example, the first output string must contain the first letter of all the input strings, the second output string must contain the second letter of all the input strings, and so on.

Examples (the numbers under the letters are the indexes of the strings):

```<code>input: "car", "dog", "man", "yay"
        012    012    012    012
output: "cdmy", "aoaa", "rgny"
         0000    1111    2222

input: "money", "taken", "trust"
        01234    01234    01234
output: "mtt", "oar", "nku", "ees", "ynt"
         000    111    222    333    444
</code>```

Assume that the input is correct everytime

Shortest bytes' code wins!

Edit:

Since there are many programming languages, and there could be many possible solutions for each of them, I will post the shortest solution for each programming language and the user who provided it. Keep coding!

Re-Edit:

Thanks to user Dennis I inserted a snippet for the leaderboards.

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Common Lisp, 62 bytes

(lambda(s)(apply'map'list(lambda(&rest x)(coerce x'string))s))

The map function takes a result type (here list), a function f to apply and one or more sequences s1, ..., sn. All sequences are iterated in parallel. For each tuple of elements (e1,...,en) taken from those sequences, we call (f e1 ... en) and the result is accumulated in a sequence of the desired type.

We take a list of strings, say ("car" "dog" "man" "yay"), and use apply to call map. We have to do this so that the input list is used as more arguments to map. More precisely, this:

(apply #'map 'list fn '("car" "dog" "man" "yay"))

... is equivalent to:

(map 'list f "car" "dog" "man" "yay")

And since strings are sequences, we iterate in parallel over all first characters, then all second characters, etc... For example, the first iteration calls f as follows:

(f #\c #\d #\m #\y)

The anonymous lambda takes the list of arguments given to it and coerces it back to a string.


答:
C++, 102 bytes

```<code>[](int i){int t;map<int,int>k;for(k[1];i--;k.erase(t))t=k.begin()->first,k[t*2+1],k[t*3-1];return t;};
</code>```

This lambda function requires #include <map> and using std::map.

The map here is just a collection of keys; their values are ignored. I use map in order to benefit from the terse code for insertion:

```<code>k[1]; // inserts the key 1 into the map
</code>```

Thanks to the sorted order of map, the smallest element is  extracted by k.begin()->first.

Title: Calculate A190810

Body:
Your task is pretty simple, calculate the n-th element of A190810.

Elements of A190810 are calculated according to these rules:

The first element is 1

The sequence is increasing

If x occurs in the sequence, then 2x+1 and 3x-1 also do

You can use 1-based or 0-based indexing, but if you use 0-based indexing, please say it in the answer.

Test cases

```<code>a(1) = 1
a(2) = 2
a(3) = 3
a(4) = 5
a(5) = 7
a(10) = 17
a(20) = 50
a(30) = 95
a(55) = 255
</code>```

Since this is code-golf, the shortest answer in bytes wins!

Body:
C++, 102 bytes

[](int i){int t;map<int,int>k;for(k[1];i--;k.erase(t))t=k.begin()->first,k[t*2+1],k[t*3-1];return t;};

This lambda function requires #include <map> and using std::map.

The map here is just a collection of keys; their values are ignored. I use map in order to benefit from the terse code for insertion:

k[1]; // inserts the key 1 into the map

Thanks to the sorted order of map, the smallest element is  extracted by k.begin()->first.


答:
Racket, <s>91</s> 82 Bytes

Old solution (based off @Zeta's solution):

```<code>(λ(n)(for*/sum([i(in-range 1(+ 1 n))][j(in-range(+ 1(- n i)))])(*(expt 26 i)(expt 10 j))))
</code>```

New solution (thanks to Neil's solution):

```<code>(λ(n)(for/sum([i(in-range 1(+ 1 n))])(*(expt 26 i)(/(-(expt 10(-(+ n 1)i))1)9))))
</code>```

Body:
In this question Tom learned that, in general, there are many motivations to choose to include case sensitivity in his programming language, because the possible combinations for a variable name are much more than what's possible with a case insensitive programming language for a name of the same length.

But, as a more meticulous person than him pointed out, even with case sensitivity, many combinations like A_18__cDfG are wasted anyway because no one will ever use them, so Tom decided to be an even more meticulous person and to redo the calculation of the difference of possibilities of variable names between a case sensitive programming language and a case insensitive programming language only counting the variable names that are likely to be used.

The Challenge

Write a function (or a full program if your language doesn't support them) that takes an input n and returns (or outputs) the difference between the number of possible, valid combinations for a variable name of length n with case sensitivity and a variable name of the same length without case sensitivity.

Valid names

You must only count names in which:

The first character is either an alphabet letter or an underscore, but never a digit;

If there are digits, they must appear at the end of the name, so that x1 and arraysize12 are valid but iam6feettall isn't;

If underscores are present, they must appear at the beginning of the name, like in __private and _VERSION but unlike in __init__ or some_variable;

For case sensitive names, variables like HeLlObOyS aren't counted. A name must be either all uppercase (HELLOBOYS) or all lowercase (helloboys);

There must be at least one alphabetic character. This means _________a9999999999 is valid but __ or _4 arent't.

Rules

Regexs are, of course, allowed;

Blame Tom's meticulousness.

Testcases

```<code>Input (lenght of the varable name) -> Output (differences in valid combinations)
0 -> 0 (no combinations for both cases: 0 - 0 = 0)
1 -> 26
2 -> 962
3 -> 27898
4 -> 754234
5 -> 19898970
6 -> 520262106
</code>```

Scoring

It's again code golf. Shortes program in bytes wins.

Reference, non-competing Lua implementation

Since the test cases may be wrong, I've been asked to include it, so here it is:

```<code>local case = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789"

local function isvalid(s)  --checks if a string s is valid AND only suitable for case sensitive
    if s:upper() == s then --if the string is all uppercase, it's also valid for case unsensitive
        return false
    end
    return (s:match"^_*[%w]+[%d]*$" --checks if it matchs the underscore-character-digit sequence
            and s:lower() == s)     --checks if it's all lowercase
            and true                --trasforms to boolean value
end

local function each(s, n) --recursive function called for character at position 2..n
    if n == 0 then
        if isvalid(s) then
            return 1
        end
        return 0
    else
        local total = 0
        for i = 1, #case do
            total = total + each(s..case:sub(i, i), n - 1)
        end
        return total
    end
end

local function diff(n) --the actual function
    local total = 0
    if n > 0 then
        for s = 1, #case - 10 do --loops for character at position 1, which can't be a digit
            total = total + each(case:sub(s, s), n - 1)
        end
    end
    print(string.format("%.0f", total)) --prints the result in non-scientific notation
end
</code>```

Body:
Racket, <s>91</s> 82 Bytes

Old solution (based off @Zeta's solution):

(λ(n)(for*/sum([i(in-range 1(+ 1 n))][j(in-range(+ 1(- n i)))])(*(expt 26 i)(expt 10 j))))

New solution (thanks to Neil's solution):

(λ(n)(for/sum([i(in-range 1(+ 1 n))])(*(expt 26 i)(/(-(expt 10(-(+ n 1)i))1)9))))


答:
Haskell, <s>76</s> <s>73</s> 69 bytes

```<code>a#b=mod a b<1&&t(div a b)
t x=x<2||(x-1)#2||(x+1)#3
(filter t[1..]!!)
</code>```

Uses a 0-based index. Usage example: (filter t[1..]!!) 54 -> 255.

Instead of building the list by repeatedly inserting 2x+1 and 3x-1 as seen in most other answers, I go through all integers and check if they can reduced to 1 by repeatedly applying (x-1) / 2 or (x+1) / 3 if divisible.

Title: Calculate A190810

Body:
Haskell, <s>76</s> <s>73</s> 69 bytes

a#b=mod a b<1&&t(div a b)
t x=x<2||(x-1)#2||(x+1)#3
(filter t[1..]!!)

Uses a 0-based index. Usage example: (filter t[1..]!!) 54 -> 255.

Instead of building the list by repeatedly inserting 2x+1 and 3x-1 as seen in most other answers, I go through all integers and check if they can reduced to 1 by repeatedly applying (x-1) / 2 or (x+1) / 3 if divisible.


问:
Calculate n Kaprekar Numbers
A Kaprekar number is an n-digit number k that, when the first n or n-1 digits of k^2 are added to the second n the digits of N^2, the result is N.

Examples:

```<code>9^2 = 81.  8+1 = 9.
45^2 = 2025.  20+25 = 45.
297^2 = 88,209. 88+209 = 297
</code>```

The Kaprekar sequence begins at 1.

Write a program that calculates and outputs the first n Kaprekar numbers, with n being in the range, but not limited to the range, of 1 to 100.  Each Kaprekar number must be separated with whitespace and nothing else.

More Kaprekar numbers can be found here to check your program against, but this resource MAY NOT be used in any way to help with the calculation - in other words, no hard-coding, reading from this source, or using it in any other exploitive way - all the numbers must be generated by your program.

Shortest code wins.

Title: Calculate n Kaprekar Numbers

Body:
C, <s>90</s> <s>76</s> 75 bytes

long long d,r=1;k(n){for(;++d/r?r*=10:--n;d-d*d/r-d*d%r||printf("%d ",d));}


答:
Emacs lisp, 106 bytes

```<code>(defmath f(n)(let((r 0))(for((k 1(1+ n)))(setq r(+ r(*(^ 26 k)(/(1-(^ 10(- n k -1)))9)))))(calc-eval r)))
</code>```

Creates a function called calcFunc-f. Pretty much the first (Emacs) lisp I've written, uses Neil's optimization.

Body:
Emacs lisp, 106 bytes

(defmath f(n)(let((r 0))(for((k 1(1+ n)))(setq r(+ r(*(^ 26 k)(/(1-(^ 10(- n k -1)))9)))))(calc-eval r)))

Creates a function called calcFunc-f. Pretty much the first (Emacs) lisp I've written, uses Neil's optimization.


答:
Clojure, 114 108 bytes

```<code>#(loop[a(sorted-set 1)n 1](let[x(first a)](if(= n %)x(recur(conj(disj a x)(+(* 2 x)1)(-(* 3 x)1))(inc n)))))
</code>```

I wouldn't be surprised if this could be golfed/reduced by a significant amount but set's not supporting nth really hurt my train of thought.

Try the online

Version with spaces:

```<code>#(loop [a (sorted-set 1)
        n 1]
  (let [x (first a)]
    (if (= n %)
      x
      (recur (conj (disj a x) (+ (* 2 x) 1) (- (* 3 x) 1)) (inc n))
      )))
</code>```

Title: Calculate A190810

Body:
Clojure, 114 108 bytes

#(loop[a(sorted-set 1)n 1](let[x(first a)](if(= n %)x(recur(conj(disj a x)(+(* 2 x)1)(-(* 3 x)1))(inc n)))))

I wouldn't be surprised if this could be golfed/reduced by a significant amount but set's not supporting nth really hurt my train of thought.

Try the online

Version with spaces:

#(loop [a (sorted-set 1)
        n 1]
  (let [x (first a)]
    (if (= n %)
      x
      (recur (conj (disj a x) (+ (* 2 x) 1) (- (* 3 x) 1)) (inc n))
      )))