问:
Flood-fill a 2D grid

Challenge description

Let's call a two-dimentional, rectangular array (meaning its every subarray has the same length), a grid. Every unit of a grid is either an empty space or a border. In a grid of characters, empty space is represented by a single whitespace; any other character is treated as a border. Sample grids (+'s, |'s and -'s added for readability - they are not part of the grid):

```<code>+----+
|    |
|    |
|    |
|    |
|    |
+----+  an empty 4x5 grid

+------+
|      |
|  #   |
|  #   |
+------+  a 6x3 grid with 2 borders

+----------+
|          |
|          |
|  #####   |
|  #   #   |
| ##   # <------ enclosed area
| #    #   |
| ######   |
|          |
+----------+  a 10x8 grid with an enclosed area
</code>```

Given a 2D grid and a pair of coordinates, fill the enclosed area surrounding the point represented by the coordinates.

Sample inputs / outputs

1)

```<code>0 0
+----------+      +----------+
|          |      |XXXXXXXXXX|
|          |  ->  |XXXXXXXXXX|
|          |      |XXXXXXXXXX|
+----------+      +----------+
</code>```

2)

```<code>6 5
+-----------------+      +-----------------+
|                 |      |                 |
|                 |      |                 |
|    ########     |      |    ########     |
|    #       #    |      |    #XXXXXXX#    |
|    #    ####    |      |    #XXXX####    |
|    #    #       |      |    #XXXX#       |
|    #    #       |  ->  |    #XXXX#       |
|    #    #       |      |    #XXXX#       |
|     ####        |      |     ####        |
|                 |      |                 |
|                 |      |                 |
+-----------------+      +-----------------+
</code>```

3)

```<code>4 6
+-----------------+      +-----------------+
|                 |      |XXXXXXXXXXXXXXXXX|
|    ####         |      |XXXX####XXXXXXXXX|
|   #    #        |  ->  |XXX#    #XXXXXXXX|
|    ####         |      |XXXX####XXXXXXXXX|
|                 |      |XXXXXXXXXXXXXXXXX|
+-----------------+      +-----------------+
</code>```

4)

```<code>4 5
+-----------------+      +-----------------+      +-----------------+
|                 |      |                 |      |                 |
|                 |      |                 |      |                 |
|    ####         |      |    ####         |      |     XXXX        |
|    ####         |  ->  |    ####         |  or  |     XXXX        |
|    ####         |      |    ####         |      |     XXXX        |
|                 |      |                 |      |                 |
+-----------------+      +-----------------+      +-----------------+
</code>```

5)

```<code>2 6
+----------------+      +----------------+
|                |      |XXXXXXXXXXXXXXXX|
|                |      |XXXXXXXXXXXXXXXX|
|                |      |XXXXXXXXXXXXXXXX|
|                |  ->  |XXXXXXXXXXXXXXXX|
|                |      |XXXXXXXXXXXXXXXX|
|BBBBBBBBBBBBBBBB|      |BBBBBBBBBBBBBBBB|
|                |      |                |
|                |      |                |
+----------------+      +----------------+
</code>```

Notes

An empty grid is considered enclosed, i.e. borders are implicitly situated along the edges of the grid as well (see examples 1. and 5.),

A corner of an enclosed area doesn't need to be L-shaped. The following two areas are therefore equivalent:

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

If a unit under the coordinates happens to be a border you can either leave the grid unchanged (as in example 4.) or treat it as an empty space,

You can choose any character for filler / empty space as long as you include this information in the submission,

If using a type other than char suits your purposes better, you can use ints (0 for empty space, 1 for border) or booleans (true and false respectively) or any other type - just make sure to include this information in your submission,

Coordinates used in the examples above are 0-indexed (row, column) coordinates, as it's more convenient for two-dimensional array. If you want to use (column, row) (cartesian) system and/or non-0-indexed coordinates, specify it in your submission.

If you don't know where to start, check out Wikipedia article on flood fill

Remember that this is a code-golf challenge, so make your code as short as possible!

答:
MATLAB, <s>30</s> 7 bytes

As we can use logical inputs instead of strings, we can use the bare function, as it is:

```<code>@imfill
</code>```

This is an anonymous function. For the usage, we have to assume a name, e.g. f=@imfill. Then we can just evaluate it as f(input,point), where input is a logical matrix, e.g. [0,0;0,1], and point is a 2d-vector with 1-based coordinates, e.g. [1,2].

Old version working on strings:

```<code>@(a,p)[imfill(a>32,p)*3+32,'']
</code>```

This anonymous function accepts the input as well as a vector with the coordinates (1-based index). The function imfill does exactly what we need, but operates only on binary images. That is why we convert the input matrix to a logical array (where # are the boundaries, and   (spaces) are the void), performs the filling and is then converted back. (again # is filled, space is not filled).

Thanks @LuisMendo for -<s>1</s> byte.

Title: Flood-fill a 2D grid

Body:
MATLAB, <s>30</s> 7 bytes

As we can use logical inputs instead of strings, we can use the bare function, as it is:

@imfill

This is an anonymous function. For the usage, we have to assume a name, e.g. f=@imfill. Then we can just evaluate it as f(input,point), where input is a logical matrix, e.g. [0,0;0,1], and point is a 2d-vector with 1-based coordinates, e.g. [1,2].

Old version working on strings:

@(a,p)[imfill(a>32,p)*3+32,'']

This anonymous function accepts the input as well as a vector with the coordinates (1-based index). The function imfill does exactly what we need, but operates only on binary images. That is why we convert the input matrix to a logical array (where # are the boundaries, and   (spaces) are the void), performs the filling and is then converted back. (again # is filled, space is not filled).

Thanks @LuisMendo for -<s>1</s> byte.


问:
Generate a valid sequence of numbers with specific rules

The challenge

The program must return a valid sequence of numbers into some rules

Rules

x is the size of the sequence;

x cannot be less than 4 or greater than 9 (Thanks David Carraher);

Digits of the sentence can't repeat, each one must appear once;

All digits between 1 to x must be in the sequence;

A valid sequence never begins nor ends with 1 or x;

Into the sequence, numbers can never appear "together";

Examples

If x=4:

2413 valid

3142 valid

1423 not valid, because begins with 1 and 23 are "together".

2134 not valid, because ends with x and 34 are "together".

Still don't get it?
Other example:

If x=8:

28375146 valid, because don't start with 1 nor x(8), don't end with 1 nor x, and no numbers are "together"(no numbers touches, no numbers are the next or previous)

Sorry, I really don't know how to explain the last rule. Hope the example make it understandable.

Additional Information

x does not need to be an input, you can show the outputs for x=4 and x=9 working;

Since any language will be accepted and, I don't know how all of them work, I will ask you people to help me with this;

The winner will be the one who got more up-votes in 1 week, so please, vote the answer you find the best; I will mark it as the Correct one;

Good, luck. =)

答:
Mathematica 38

This simply returns the digits less than or equal to x, in the order in which they appear below.

```<code>Row@Select[{2, 9, 6, 4, 7, 1, 8, 5, 3},#<x+1&]
</code>```

The results from 4 through 9:

ContentLicense: CC BY-SA 3.0

Body:
Mathematica 38

This simply returns the digits less than or equal to x, in the order in which they appear below.

Row@Select[{2, 9, 6, 4, 7, 1, 8, 5, 3},#<x+1&]

The results from 4 through 9:


问:
The Doughnut Shop™
Being short of cash, you have signed up to build donuts for The Doughnut Shop™, the biggest digital doughnut company in the world, mostly because they sell every size of doughnut imaginable.

Now, given that trading standards nowadays is very tough, you need to write a piece of code as short as possible to create these doughnuts so that the source code that created them can be put on the outside of the packet.

Challenge

Given 4 inputs, radius of the outer ring, radius of the inner ring, the possible sprinkles and the chance of a cell having a sprinkle, output a doughnut covered in those sprinkles which has the correct inner and outer radii.

The input may be taken how you wish (arguments to a function, stdin, program arguments) and in any order.

The sprinkles will be given in the form of 1 character per sprinkle type

^+*- as sprinkle input would be a list of 4 sprinkles, ^, +, *, -

The chance of a sprinkle will be entered as a floating point value between 0 and 1. eg: 0.1, 0.23

You must print out the output to stdout or equivalent.

Sprinkles can't be on the edges of the doughnut.

Each type of sprinkle must have an equally likely chance of being on each cell.

The radii are given in 1-cell units.

If the inner radius equals either 0 OR the outer radius, the doughnut is said to have no ring.

Both radii will be non-negative integers.

The inner and outer edges of the doughnut must be represented using hashes (#)

A test to see if a point is in a circle, given a radius and the center of the circle is:

(x-center)**2+(y-center)**2 < radius**2

Example input with output

(outer radius, inner radius, sprinkles, chance of sprinkle)

10, 4, "^+*-", 0.1

```<code>     #########
    #         #
  ##  ++   *  *##
  #             #
 #       ^^ - *  #
#      #####   ^  #
#+    #     #     #
#    #       #-   #
#    #       #  * #
#    #       #+   #
#    #       #    #
#^  +#       #    #
#     #     #     #
# *    #####      #
 #       +  -    #
  #        ^    #
  ##  ^  +     ##
    #       ^ #
     #########
</code>```

5, 2, ":^+*", 0.9

```<code>  #####
 #^^+ ^#
#**###  #
#:#   #^#
#^#   #*#
#:#   #*#
#:+###* #
 # *:^:#
  #####
</code>```

This is code golf, the shortest answer in bytes wins

答:
MATLAB, 231 bytes

Here a matlab solution:

```<code>function g=z(r,q,s,p);[x,y]=meshgrid(1:2*r,1:2*r);d=(x-r).^2+(y-r).^2;h=size(d);e=zeros(h);e(d<r^2 & d>=q^2)=1;f=bwperim(e,4);k=rand(h);j=numel(s);l=changem(randi(j,h),s,1:j);g=char(e);g(:,:)=' ';g(k<=p)=l(k<=p);g(f)='#';g(~e)=' ';
</code>```

Some examples:

```<code>>> z(10, 4, '^+*-', 0.1)

ans =

     #########
    #         #
  ##           ##
  #    -       -#
 #               #
#   -  #####    ^ #
#     #     #     #
#   -#       #    #
# *  #       #+   #
#**  #       #    #
#  * #       # -  #
#+  *#       #    #
#     #     #     #
#      #####      #
 #           ^   #
  #     *       #
  ##+          ##
    #         #
     #########

>> z(5, 2, ':^+*', 0.9)

ans =

  #####
 #++::*#
#^^###++#
# #   #+#
#^#   #^#
#*#   #*#
#+:###^*#
 #*:^+^#
  #####

>> z(20,6, 'erthhjjjjkjkk', 0.4)

ans =

             #############
           ##jh  k  k  k  ##
         ##  jjj    j khh   ##
        #r kj h   k tjhj j    #
      ##jk    t k  jh j       h##
     #k       rre            k j #
    # j   j j  j  khtkt jr     kj #
    #  k   rk je    j      h   j  #
   # j   k   k  jth e k j   j    j #
  #h   h h e     t e ej  j  r k r e #
  #    j   r  jh  jk     j  kk   j  #
 #      k     k    h k  jk     k j   #
 #  jjk   hh k hj  r  j  je rjj k j  #
#  ek  j j jj  h#######          hke  #
#hj      k j j #       #ke jhkt  jee  #
#        jk  k#         # k    j   t  #
#k        j  #           #khk  r     j#
#   tj  j te #           # j  r j j   #
#e   je   jhk#           #        t j #
#jj    j  h  #           #     k jj e #
# j j   hj j #           # jkt kjjjr e#
#j k    e    #           #       r   k#
#jj  k    ek #           # hj  j rtj  #
#   k j   hk h#         #     j  h j  #
#   h trt  jrht#       #   et        k#
#j  ehjj      j #######ett  kh kjj k  #
 #   r  jj    ekk jk    th k   kkk h #
 #hj       khe kj hr  jj   kk  r j   #
  #r t    k j  k r  j  jk k hh    jj#
  #  kjj  h k j       j rrr j  r j  #
   #j kej  jj    t       h  j   hh #
    #  he   e  tje j  tjhkjk kj   #
    #j kt rjk    j j  ee    rkj   #
     #   jjr e  j jkt j   e  j  j#
      ##k  thhjj je   kj  kh   ##
        # hje  j     jj kk t j#
         ## k       h     e ##
           ## e jje   kkhj##
             #############
</code>```

Title: The Doughnut Shop™

Body:
MATLAB, 231 bytes

Here a matlab solution:

function g=z(r,q,s,p);[x,y]=meshgrid(1:2*r,1:2*r);d=(x-r).^2+(y-r).^2;h=size(d);e=zeros(h);e(d<r^2 & d>=q^2)=1;f=bwperim(e,4);k=rand(h);j=numel(s);l=changem(randi(j,h),s,1:j);g=char(e);g(:,:)=' ';g(k<=p)=l(k<=p);g(f)='#';g(~e)=' ';

Some examples:

>> z(10, 4, '^+*-', 0.1)

ans =

     #########
    #         #
  ##           ##
  #    -       -#
 #               #
#   -  #####    ^ #
#     #     #     #
#   -#       #    #
# *  #       #+   #
#**  #       #    #
#  * #       # -  #
#+  *#       #    #
#     #     #     #
#      #####      #
 #           ^   #
  #     *       #
  ##+          ##
    #         #
     #########

>> z(5, 2, ':^+*', 0.9)

ans =

  #####
 #++::*#
#^^###++#
# #   #+#
#^#   #^#
#*#   #*#
#+:###^*#
 #*:^+^#
  #####

>> z(20,6, 'erthhjjjjkjkk', 0.4)

ans =

             #############
           ##jh  k  k  k  ##
         ##  jjj    j khh   ##
        #r kj h   k tjhj j    #
      ##jk    t k  jh j       h##
     #k       rre            k j #
    # j   j j  j  khtkt jr     kj #
    #  k   rk je    j      h   j  #
   # j   k   k  jth e k j   j    j #
  #h   h h e     t e ej  j  r k r e #
  #    j   r  jh  jk     j  kk   j  #
 #      k     k    h k  jk     k j   #
 #  jjk   hh k hj  r  j  je rjj k j  #
#  ek  j j jj  h#######          hke  #
#hj      k j j #       #ke jhkt  jee  #
#        jk  k#         # k    j   t  #
#k        j  #           #khk  r     j#
#   tj  j te #           # j  r j j   #
#e   je   jhk#           #        t j #
#jj    j  h  #           #     k jj e #
# j j   hj j #           # jkt kjjjr e#
#j k    e    #           #       r   k#
#jj  k    ek #           # hj  j rtj  #
#   k j   hk h#         #     j  h j  #
#   h trt  jrht#       #   et        k#
#j  ehjj      j #######ett  kh kjj k  #
 #   r  jj    ekk jk    th k   kkk h #
 #hj       khe kj hr  jj   kk  r j   #
  #r t    k j  k r  j  jk k hh    jj#
  #  kjj  h k j       j rrr j  r j  #
   #j kej  jj    t       h  j   hh #
    #  he   e  tje j  tjhkjk kj   #
    #j kt rjk    j j  ee    rkj   #
     #   jjr e  j jkt j   e  j  j#
      ##k  thhjj je   kj  kh   ##
        # hje  j     jj kk t j#
         ## k       h     e ##
           ## e jje   kkhj##
             #############


问:
Falling ASCII balls

Input

You are given a 2D map with balls and ground in it.
It looks like this:

```<code>  1         5          2
                 3
     4

__________________________
</code>```

Each number is a ball, and the _ is ground level. The underscore _ character is not allowed in any other line than ground level line. There are only spaces, newlines and digits 0-9 allowed above ground level. You cannot assume that last line is the ground level - empty lines below ground level are allowed. You can also add spaces, to fill empty lines, if that does help you.

Balls can have numbers from 0 to 9, can be placed above each other, but not under ground. The ball's numbers will be unique.

Assume that each character is one meter.

Get map from pastebin!

Test case 1 - should output something like this

Test case 2 - should produce same results as first map

Challenge

Your challenge is to read a map like that from a file or from stdin — you are allowed to use cat balls.txt | ./yourexecutable — and output velocity of each ball when it hits the ground.

Here's the formula for velocity:

Assume that h is the line number difference between the ground's line number, and the ball's line number, and that g equals 10m/s^2.

Output

You should output each balls number and velocity in m/s at ground level.
For example N - Vm/s, where N is ball number and V is its velocity.
You can also output an array if you want.

Happy coding! :)

答:
JavaScript (ES6) 93

Edit 2 bytes saved thx @Jacajack

A function with a multiline string as input parameter. Output is not sorted (as this in not requested)

```<code>a=>[...a].reverse().map(c=>c>'Z'?b=i:c<' '?++i:c>' '&&console.log(c,Math.sqrt((i-b)*20)),i=0)
</code>```

Test

F=
a=>[...a].reverse().map(c=>c>'Z'?b=i:c<' '?++i:c>' '&&console.log(c,Math.sqrt((i-b)*20)),i=0)

function test()
{
  F(I.value);
}

test()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#I { height: 12em; width: 30em}</code>```

<textarea id=I>

  1         5          2
                 3
     4

__________________________

</textarea>
<button onclick="test()"></button>```

Title: Falling ASCII balls

Body:
JavaScript (ES6) 93

Edit 2 bytes saved thx @Jacajack

A function with a multiline string as input parameter. Output is not sorted (as this in not requested)

a=>[...a].reverse().map(c=>c>'Z'?b=i:c<' '?++i:c>' '&&console.log(c,Math.sqrt((i-b)*20)),i=0)

Test

F=
a=>[...a].reverse().map(c=>c>'Z'?b=i:c<' '?++i:c>' '&&console.log(c,Math.sqrt((i-b)*20)),i=0)

function test()
{
  F(I.value);
}

test()

#I { height: 12em; width: 30em}

<textarea id=I>

  1         5          2
                 3
     4

__________________________

</textarea>
<button onclick="test()"></button>


问:
Build a marginal tax calculator
There have been some tax rate calculator problems here that depend on defined rates (specifically US federal rates), but none that have done it for arbitrary lists.

Your task is to build a program or function that will take an arbitrary list of marginal tax brackets and calculate the effective amount of tax paid on a given amount of taxable income.

Your program will take as input:

N pairs of numbers in the form (amt, rate), each representing a tax bracket.

amt is the amount of taxable income above which at which the tax rate starts to apply. These amounts will all be integers, and appear in increasing order.

rate is the tax rate, expressed as a decimal percentage from 0 to 100 inclusive.

The amount of taxable income, as a nonnegative integer.

If no rate is specified for $0, the rate is assumed to be 0%.

Alternatively, your program can also take as input two lists (amt1, amt2, ...) and (rate1, rate2, ...), containing the amounts and rates in the same order.

Your program will then output the payable tax, either to two decimal places, or rounded down to the nearest whole currency unit.

An example input (the most recent Canadian tax brackets, from 2016, with the basic personal tax credit applied and nothing else):

```<code>11474 15
45282 20.5
90563 26
140388 29
200000 33

393216
</code>```

And its corresponding output:

```<code>108357.07  or  108357
</code>```

The shortest program in any language to do this wins.

Title: Build a marginal tax calculator

Body:
JavaScript (ES6), 60 bytes

(a,n)=>a.map(([b,r])=>{t+=n>b&&(n-b)*(r-p);p=r},p=t=0)|t/100

a is an array of arrays of band and rate, which would be [[11474, 15], [45282, 20.5], [90563, 26], [140388, 29], [200000, 33]] for the given example, and n is the income (393216).


问:
Simplify a square root
Given a positive integer n, simplify the square root √n into the form a√b by extracting all square factors. The outputted a,b should be positive integers with n = a^2 * b with b as small as possible.

You may output a and b in either order in any reasonable format. You may not omit outputs of 1 as implicit.

The outputs for n=1..36 as (a,b):

```<code>1 (1, 1)
2 (1, 2)
3 (1, 3)
4 (2, 1)
5 (1, 5)
6 (1, 6)
7 (1, 7)
8 (2, 2)
9 (3, 1)
10 (1, 10)
11 (1, 11)
12 (2, 3)
13 (1, 13)
14 (1, 14)
15 (1, 15)
16 (4, 1)
17 (1, 17)
18 (3, 2)
19 (1, 19)
20 (2, 5)
21 (1, 21)
22 (1, 22)
23 (1, 23)
24 (2, 6)
25 (5, 1)
26 (1, 26)
27 (3, 3)
28 (2, 7)
29 (1, 29)
30 (1, 30)
31 (1, 31)
32 (4, 2)
33 (1, 33)
34 (1, 34)
35 (1, 35)
36 (6, 1)
</code>```

These are OEIS A000188 and A007913.

Related: A more complex version.

var QUESTION_ID=83814,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/83814/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

```

答:
Jelly, 9 bytes

```<code>ÆE;0d2ZÆẸ
</code>```

Try it online! or verify all test cases.

How it works

```<code>ÆE;0d2ZÆẸ  Main link. Argument: n

ÆE         Exponents; generate the exponents of n's prime factorization.
  ;0       Append 0 since 1ÆE returns [].
    d2     Divmod by 2.
      Z    Zip/transpose to group quotients and remainders.
       ÆẸ  Unexponent; turn the exponents of prime factorizations into integers.
</code>```

Title: Simplify a square root

Body:
Jelly, 9 bytes

ÆE;0d2ZÆẸ

Try it online! or verify all test cases.

How it works

ÆE;0d2ZÆẸ  Main link. Argument: n

ÆE         Exponents; generate the exponents of n's prime factorization.
  ;0       Append 0 since 1ÆE returns [].
    d2     Divmod by 2.
      Z    Zip/transpose to group quotients and remainders.
       ÆẸ  Unexponent; turn the exponents of prime factorizations into integers.


Title: Build a marginal tax calculator

Body:
There have been some tax rate calculator problems here that depend on defined rates (specifically US federal rates), but none that have done it for arbitrary lists.

Your task is to build a program or function that will take an arbitrary list of marginal tax brackets and calculate the effective amount of tax paid on a given amount of taxable income.

Your program will take as input:

N pairs of numbers in the form (amt, rate), each representing a tax bracket.

amt is the amount of taxable income above which at which the tax rate starts to apply. These amounts will all be integers, and appear in increasing order.

rate is the tax rate, expressed as a decimal percentage from 0 to 100 inclusive.

The amount of taxable income, as a nonnegative integer.

If no rate is specified for $0, the rate is assumed to be 0%.

Alternatively, your program can also take as input two lists (amt1, amt2, ...) and (rate1, rate2, ...), containing the amounts and rates in the same order.

Your program will then output the payable tax, either to two decimal places, or rounded down to the nearest whole currency unit.

An example input (the most recent Canadian tax brackets, from 2016, with the basic personal tax credit applied and nothing else):

```<code>11474 15
45282 20.5
90563 26
140388 29
200000 33

393216
</code>```

And its corresponding output:

```<code>108357.07  or  108357
</code>```

The shortest program in any language to do this wins.

Body:
Mathematica <s>85</s>  82 bytes

Derived from Josh O'Brien's code in R.

d_~f~i_:=Tr@Thread[Differences@((i~Min~#&/@d[[All,1]]~Append~∞))d[[All,2]]/100.]

Usage

f[{{11474, 15}, {45282, 20.5}, {90563, 26}, {140388, 29}, {200000, 33}}, 393216]

108357.


答:
Pyth, 15 bytes

```<code>/Q^
ef!%Q^T2SQ2
</code>```

Test suite.

Title: Simplify a square root

Body:
Given a positive integer n, simplify the square root √n into the form a√b by extracting all square factors. The outputted a,b should be positive integers with n = a^2 * b with b as small as possible.

You may output a and b in either order in any reasonable format. You may not omit outputs of 1 as implicit.

The outputs for n=1..36 as (a,b):

```<code>1 (1, 1)
2 (1, 2)
3 (1, 3)
4 (2, 1)
5 (1, 5)
6 (1, 6)
7 (1, 7)
8 (2, 2)
9 (3, 1)
10 (1, 10)
11 (1, 11)
12 (2, 3)
13 (1, 13)
14 (1, 14)
15 (1, 15)
16 (4, 1)
17 (1, 17)
18 (3, 2)
19 (1, 19)
20 (2, 5)
21 (1, 21)
22 (1, 22)
23 (1, 23)
24 (2, 6)
25 (5, 1)
26 (1, 26)
27 (3, 3)
28 (2, 7)
29 (1, 29)
30 (1, 30)
31 (1, 31)
32 (4, 2)
33 (1, 33)
34 (1, 34)
35 (1, 35)
36 (6, 1)
</code>```

These are OEIS A000188 and A007913.

Related: A more complex version.

var QUESTION_ID=83814,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/83814/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:
Pyth, 15 bytes

/Q^
ef!%Q^T2SQ2

Test suite.


答:
Python 2, 43 bytes

k=n=input()
while n%k**2:k-=1
print k,n/k/k
```

Test it on Ideone.

Title: Simplify a square root

Body:
Python 2, 43 bytes

k=n=input()
while n%k**2:k-=1
print k,n/k/k

Test it on Ideone.


问:
Is string X a subsequence of string Y?
Given strings X and Y, determine whether X is a subsequence of Y. The empty string is regarded as a subsequence of every string. (E.g., '' and 'anna' are subsequences of 'banana'.)

Input

X, a possibly-empty case-sensitive alphanumeric string

Y, a possibly-empty case-sensitive alphanumeric string

Output

True or False (or equivalents), correctly indicating whether X is a subsequence of Y.

I/O examples

```<code>X      Y        output

''     'z00'    True
'z00'  'z00'    True
'z00'  '00z0'   False
'aa'   'anna'   True
'anna' 'banana' True
'Anna' 'banana' False
</code>```

Criteria

The shortest program wins, as determined by the number of bytes of source code.

Example programs

Several programs that could be adapted are in this related posting.

答:
Python 132

Similar to Daniero's. Not the easiest solution, but it was fun to try. I'm new to Python, so I'm sure I could make it shorter if I knew a little bit more.

```<code>def f(i):
    s=x;j=0
    while j<len(s):t=~i%2;s=[s[:j]+s[j+1:],s][t];j+=t;i>>=1
    return s==y
print True in map(f,range(1,2**len(x)))
</code>```

ContentLicense: CC BY-SA 4.0

Title: Is string X a subsequence of string Y?

Body:
Python 132

Similar to Daniero's. Not the easiest solution, but it was fun to try. I'm new to Python, so I'm sure I could make it shorter if I knew a little bit more.

def f(i):
    s=x;j=0
    while j<len(s):t=~i%2;s=[s[:j]+s[j+1:],s][t];j+=t;i>>=1
    return s==y
print True in map(f,range(1,2**len(x)))


问:
Ninja Assassins - which ninja stays alive?

Ninja Assassins - which ninja stays alive

some basic information

given an int N as the number of ninjas, return the number of the winning ninja.

At the end only 1 ninja survives,the question is which one? what was his number?.

Each ninja kills the ninja who stands after him. Afterwards, he passes the sword to the first alive ninja who stood after the killed one.

Explenation - How the Game Works

The ninjas are numbered from 1 to N and stand in a circle according to the numbers. The circle goes clockwise: ninja 2 is left to ninja 1, ninja 3 is left to ninja 2, ninja 4 is left to ninja 3.... ninja 1 is left to ninja N.

Ninja 1 gets a sword and the game begins:

Each ninja (starting from ninja 1) kills the closest and alive ninja he has to the left (clockwise) . Afterwards, he passes the sword to the 2nd closest and alive ninja he has to the left.The 2nd ninja does the same (kills and passes) (as an example: N=3(we have 3 ninjas), ninja 1 kills ninja 2 and gives the sword to ninja 3. Ninja 3 has ninja 1 as his closest and alive ninja to the left(clockwise - its a circle) so he kills ninja 1, stays the last ninja alive and wins (so the output\return is 3, as the number of the ninja)).

A more detailed example below

Example - Word-detailed scenario

N = 7 (we got 7 ninjas) :

```<code>1 2 3 4 5 6 7 (L=alive, D=dead)
L D L L L L L The first ninja gets the sword and kills the 2nd ninja.
              The first ninja passes the sword to the 3rd ninja.
L D L D L L L The 3rd ninja gets the sword and kills the 4th ninja.
              The 3rd Ninja passes the sword to the 5th ninja.
L D L D L D L The 5th ninja gets the sword and kills the 6th ninja.
              The 5th Ninja passes the sword to the 7th ninja.
D D L D L D L The 7th ninja gets the sword and kills the first(1st) ninja.
              The 7th ninja passes the sword to the 3rd ninja.
D D L D D D L The 3rd ninja gets the sword and kills the 5th ninja.
              The 3rd ninja passes the sword to the 7th ninja.
D D D D D D L The 7th ninja gets the sword and kills the 3rd ninja,
              stays as the last one alive and wins (the final result /
              the output is 7).
</code>```

More scenarios without words

N=3 : 1 2 3 - 1 3 - 3 wins

N=4 : 1 2 3 4 - 1 3 - 1 wins

N=5 : 1 2 3 4 5 - 1 3 5 - 3 5 - 3 wins

N=6 : 1 2 3 4 5 6 - 1 3 5 - 1 5 - 5 wins

N=7 : 1 2 3 4 5 6 7 - 1 3 5 7 - 3 7 - 7 wins

Scoring is based on the least number of bytes used, as this is a code-golf question.

答:
Java 7, <s>65</s> 53 bytes

```<code>int f(int n){return(n-Integer.highestOneBit(n))*2+1;}
</code>```

Using the algorithm for k=2 Josephus from Wikipedia. Thanks to Leaky Nun for finding the builtin.

Body:
Java 7, <s>65</s> 53 bytes

int f(int n){return(n-Integer.highestOneBit(n))*2+1;}

Using the algorithm for k=2 Josephus from Wikipedia. Thanks to Leaky Nun for finding the builtin.


答:
Pyth, <s>22</s> <s>13</s> <s>12</s> 9 bytes

Credits to Geobit's algorithm for saving 9 bytes. It works like magic.

Credits to xnor's witchcraft for saving 3 bytes. It is simply witchcraft.

```
<s>heu+G=Z%e.f!/G%ZQ2ZQQY</s>
<s>u?sIlH1+2GSQ1</s>
<s>hyaefgQT^L2</s>
i.<.BQ1 2
```

Test suite.

Title: Ninja Assassins - which ninja stays alive?

Body:
Ninja Assassins - which ninja stays alive

some basic information

given an int N as the number of ninjas, return the number of the winning ninja.

At the end only 1 ninja survives,the question is which one? what was his number?.

Each ninja kills the ninja who stands after him. Afterwards, he passes the sword to the first alive ninja who stood after the killed one.

Explenation - How the Game Works

The ninjas are numbered from 1 to N and stand in a circle according to the numbers. The circle goes clockwise: ninja 2 is left to ninja 1, ninja 3 is left to ninja 2, ninja 4 is left to ninja 3.... ninja 1 is left to ninja N.

Ninja 1 gets a sword and the game begins:

Each ninja (starting from ninja 1) kills the closest and alive ninja he has to the left (clockwise) . Afterwards, he passes the sword to the 2nd closest and alive ninja he has to the left.The 2nd ninja does the same (kills and passes) (as an example: N=3(we have 3 ninjas), ninja 1 kills ninja 2 and gives the sword to ninja 3. Ninja 3 has ninja 1 as his closest and alive ninja to the left(clockwise - its a circle) so he kills ninja 1, stays the last ninja alive and wins (so the output\return is 3, as the number of the ninja)).

A more detailed example below

Example - Word-detailed scenario

N = 7 (we got 7 ninjas) :

```<code>1 2 3 4 5 6 7 (L=alive, D=dead)
L D L L L L L The first ninja gets the sword and kills the 2nd ninja.
              The first ninja passes the sword to the 3rd ninja.
L D L D L L L The 3rd ninja gets the sword and kills the 4th ninja.
              The 3rd Ninja passes the sword to the 5th ninja.
L D L D L D L The 5th ninja gets the sword and kills the 6th ninja.
              The 5th Ninja passes the sword to the 7th ninja.
D D L D L D L The 7th ninja gets the sword and kills the first(1st) ninja.
              The 7th ninja passes the sword to the 3rd ninja.
D D L D D D L The 3rd ninja gets the sword and kills the 5th ninja.
              The 3rd ninja passes the sword to the 7th ninja.
D D D D D D L The 7th ninja gets the sword and kills the 3rd ninja,
              stays as the last one alive and wins (the final result /
              the output is 7).
</code>```

More scenarios without words

N=3 : 1 2 3 - 1 3 - 3 wins

N=4 : 1 2 3 4 - 1 3 - 1 wins

N=5 : 1 2 3 4 5 - 1 3 5 - 3 5 - 3 wins

N=6 : 1 2 3 4 5 6 - 1 3 5 - 1 5 - 5 wins

N=7 : 1 2 3 4 5 6 7 - 1 3 5 7 - 3 7 - 7 wins

Scoring is based on the least number of bytes used, as this is a code-golf question.

Body:
Pyth, <s>22</s> <s>13</s> <s>12</s> 9 bytes

Credits to Geobit's algorithm for saving 9 bytes. It works like magic.

Credits to xnor's witchcraft for saving 3 bytes. It is simply witchcraft.

<s>heu+G=Z%e.f!/G%ZQ2ZQQY</s>
<s>u?sIlH1+2GSQ1</s>
<s>hyaefgQT^L2</s>
i.<.BQ1 2

Test suite.


答:
Python 2, 32 bytes

a=lambda n:n and(n%2+a(n/2))*2-1
```

<hr>

<p><strong>33 bytes:</strong></p>

<pre class="lang-python prettyprint-override"><code>a=lambda n:n and 2*a(n/2)-(-1)**n
</code>```

Uses the recursive formula on the OEIS page.

a(2*n) = 2*a(n)-1

a(2*n+1) = 2*a(n)+1

Body:
Python 2, 32 bytes

a=lambda n:n and(n%2+a(n/2))*2-1

33 bytes:

a=lambda n:n and 2*a(n/2)-(-1)**n

Uses the recursive formula on the OEIS page.

a(2*n) = 2*a(n)-1

a(2*n+1) = 2*a(n)+1


答:
VBA, 57 67 bytes

Well, this technically ought to work (57 bytes):

```<code>Function Z(N):Z=2*(N-2^Int(Log(N)/Log(2)))+1:End Function
</code>```

But actually, because occasionally the log value of a power of two is not quite an exact multiple of the log of 2, we need a few more bytes:

```<code>Function Z(N):Z=2*(N-2^Int(Log(N)/Log(2))):Z=1-Z*(Z<N):End Function
</code>```

If there were a built-in binary converter, it would be much shorter.

The recursion version is a tie, basically, but needs a line-feed for the IF

```<code>Function Y(N):Y=1:If N>1 Then Y=2*Y(N\2)+2*(N\2=N/2)+1
End Function
</code>```

Body:
VBA, 57 67 bytes

Well, this technically ought to work (57 bytes):

Function Z(N):Z=2*(N-2^Int(Log(N)/Log(2)))+1:End Function

But actually, because occasionally the log value of a power of two is not quite an exact multiple of the log of 2, we need a few more bytes:

Function Z(N):Z=2*(N-2^Int(Log(N)/Log(2))):Z=1-Z*(Z<N):End Function

If there were a built-in binary converter, it would be much shorter.

The recursion version is a tie, basically, but needs a line-feed for the IF

Function Y(N):Y=1:If N>1 Then Y=2*Y(N\2)+2*(N\2=N/2)+1
End Function


答:
Python 2, 30 bytes

lambda n:int(bin(n)[3:]+'1',2)
```

Takes the binary expansion of n and moves the initial 1 to the end.

Body:
Python 2, 30 bytes

lambda n:int(bin(n)[3:]+'1',2)

Takes the binary expansion of n and moves the initial 1 to the end.


答:
Jelly, 4 bytes

Since xnor came up with this algorithm, I will make this community wiki.

```
Bṙ1Ḅ
```

Try it online!

Explanation

```<code>Bṙ1Ḅ
B     convert to binary
 ṙ1   left-rotate by 1
   Ḅ  convert from binary
</code>```

Body:
Jelly, 4 bytes

Since xnor came up with this algorithm, I will make this community wiki.

Bṙ1Ḅ

Try it online!

Explanation

Bṙ1Ḅ
B     convert to binary
 ṙ1   left-rotate by 1
   Ḅ  convert from binary


答:
MATL, 12 bytes

```<code>t:U\~f0)GyU/
</code>```

Try it online!

Explanation

```<code>t     % Take input n implicitly. Duplicate
:U    % Push [1 4 9 ... n^2]
\~    % True for entries that divide the input
f0)   % Get (1-based) index of the last (i.e. largest) dividing number
G     % Push input again
y     % Duplicate index of largest dividing number
U     % Square to recover largest dividing number
/     % Divide input by that. Implicitly display stack
</code>```

Title: Simplify a square root

Body:
MATL, 12 bytes

t:U\~f0)GyU/

Try it online!

Explanation

t     % Take input n implicitly. Duplicate
:U    % Push [1 4 9 ... n^2]
\~    % True for entries that divide the input
f0)   % Get (1-based) index of the last (i.e. largest) dividing number
G     % Push input again
y     % Duplicate index of largest dividing number
U     % Square to recover largest dividing number
/     % Divide input by that. Implicitly display stack


答:
Julia, 32 bytes

\(n,k=n)=n%k^2>0?n\~-k:[k,n/k^2]
```

Try it online!

Title: Simplify a square root

Body:
Julia, 32 bytes

\(n,k=n)=n%k^2>0?n\~-k:[k,n/k^2]

Try it online!


答:
J, 10 bytes

```<code>(1&|.)&.#:
</code>```

Using the formula where a(n) = n written in binary and rotated left by 1 place. Similar to what is used in @xnor's solution.

Using 19 bytes, we can play the game according to the rules in the challenge.

```<code>[:(2&}.,{.)^:_>:@i.
</code>```

This solution only performs array manipulation in order to reach a final player.

Usage

Extra commands used for formatting multiple input/output with multiple functions.

```<code>   f =: (1&|.)&.#:
   g =: [:(2&}.,{.)^:_>:@i.
   (,.f"0,.g"0) i. 10
0 0 0
1 1 1
2 1 1
3 3 3
4 1 1
5 3 3
6 5 5
7 7 7
8 1 1
9 3 3
</code>```

Explanation

```<code>(1&|.)&.#:  Input: n
        #:  Convert to binary
(    )&.    Compose next function on the binary value
 1&|.       Rotate left by 1 place
(    )&.    Compose the inverse of the previous function on the result
        #:  The inverse: convert from binary to decimal and return result

[:(2&}.,{.)^:_>:@i.  Input: n
                 i.  Creates the range [0, 1, ..., n-1]
              >:@    Increment each in the range to get [1, 2, ..., n]
[:(       )^:_       Nest the function until the result does not change and return
   2&}.              Drop the first two items in the list
        {.           Get the head of the list
       ,             Join them together. This makes it so that the head of the list
                     is always the current player and the one after the head is the
                     player to be removed
</code>```

Body:
J, 10 bytes

(1&|.)&.#:

Using the formula where a(n) = n written in binary and rotated left by 1 place. Similar to what is used in @xnor's solution.

Using 19 bytes, we can play the game according to the rules in the challenge.

[:(2&}.,{.)^:_>:@i.

This solution only performs array manipulation in order to reach a final player.

Usage

Extra commands used for formatting multiple input/output with multiple functions.

   f =: (1&|.)&.#:
   g =: [:(2&}.,{.)^:_>:@i.
   (,.f"0,.g"0) i. 10
0 0 0
1 1 1
2 1 1
3 3 3
4 1 1
5 3 3
6 5 5
7 7 7
8 1 1
9 3 3

Explanation

(1&|.)&.#:  Input: n
        #:  Convert to binary
(    )&.    Compose next function on the binary value
 1&|.       Rotate left by 1 place
(    )&.    Compose the inverse of the previous function on the result
        #:  The inverse: convert from binary to decimal and return result

[:(2&}.,{.)^:_>:@i.  Input: n
                 i.  Creates the range [0, 1, ..., n-1]
              >:@    Increment each in the range to get [1, 2, ..., n]
[:(       )^:_       Nest the function until the result does not change and return
   2&}.              Drop the first two items in the list
        {.           Get the head of the list
       ,             Join them together. This makes it so that the head of the list
                     is always the current player and the one after the head is the
                     player to be removed


答:
PARI/GP, 12 bytes

```<code>n->core(n,1)
</code>```

core returns the squarefree part of n by default, but setting the second argument flag to 1 makes it return both parts. Output order is (b, a), e.g. (n->core(n,1))(12) -> [3, 2].

Title: Simplify a square root

Body:
PARI/GP, 12 bytes

n->core(n,1)

core returns the squarefree part of n by default, but setting the second argument flag to 1 makes it return both parts. Output order is (b, a), e.g. (n->core(n,1))(12) -> [3, 2].


问:
Calculate the nth term of Golomb's self-describing sequence
Inspired by the previous question.

Golomb's self-describing sequence g(n) is a sequence where any natural number n is repeated within the sequence g(n) times.

The first few numbers in the sequence are:

```<code>n    1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20
g(n) 1  2  2  3  3  4  4  4  5  5  5  6  6  6  6  7  7  7  7  8
</code>```

You can see that g(4)=3, and that "4" is repeated 3 times in the sequence.

Given an input of n, output g(n).

Limitations: n < 100000.

Smallest code wins.

答:
PHP - 63 Chars

```<code>function g($n){for(;++$i<=$n;){for(;++$j<=$i;){echo $i;}$j=0;}}
</code>```

Fast AND short.

I appear to have had the wrong sequence in mind. Derp.

This is CORRECT, fast, and short.

```<code>function g($n){for(;++$i<$n;){echo round(1.201*pow($i,.618));}}
</code>```

Accuracy may suffer past the required 100,000 mark, but I did in fact meet the mark.

Body:
PHP - 63 Chars

function g($n){for(;++$i<=$n;){for(;++$j<=$i;){echo $i;}$j=0;}}

Fast AND short.

I appear to have had the wrong sequence in mind. Derp.

This is CORRECT, fast, and short.

function g($n){for(;++$i<$n;){echo round(1.201*pow($i,.618));}}

Accuracy may suffer past the required 100,000 mark, but I did in fact meet the mark.


答:
Python, 29 bytes

f=lambda n:n&n-1<1or f(n-1)+2
```
<p>Outputs 1 as <code>True</code> when <code>n</code> is a power of 2, checked by <code>n&n-1</code> being 0. Otherwise, outputs <code>2</code> higher than the previous value.</p>
<hr />
<p><strong>28 bytes:</strong></p>
<p>Adapting grc's general solution to the case <code>k=2</code> gives a better solution</p>
<pre class="lang-python prettyprint-override"><code>f=lambda n:n and-~f(n-1)%n+1
</code>```

Rather than explicitly checking for powers of 2, it zeroes out the result before incrementing each time f(n-1) catches up to n-1

Body:
Python, 29 bytes

f=lambda n:n&n-1<1or f(n-1)+2

Outputs 1 as True when n is a power of 2, checked by n&n-1 being 0. Otherwise, outputs 2 higher than the previous value.

28 bytes:

Adapting grc's general solution to the case k=2 gives a better solution

f=lambda n:n and-~f(n-1)%n+1

Rather than explicitly checking for powers of 2, it zeroes out the result before incrementing each time f(n-1) catches up to n-1


答:
Matlab, 51 bytes

```<code>x=input('');y=1:x;z=y(~rem(x,y.^2));a=z(end)
x/a^2
</code>```

Explanation

```<code>x=input('')       -- takes input
y=1:x             -- numbers from 1 to x
z=y(~rem(x,y.^2)) -- numbers such that their squares divide x
a=z(end)          -- biggest such number (first part of output)
x/a^2             -- remaining part
</code>```

Title: Simplify a square root

Body:
Given a positive integer n, simplify the square root √n into the form a√b by extracting all square factors. The outputted a,b should be positive integers with n = a^2 * b with b as small as possible.

You may output a and b in either order in any reasonable format. You may not omit outputs of 1 as implicit.

The outputs for n=1..36 as (a,b):

```<code>1 (1, 1)
2 (1, 2)
3 (1, 3)
4 (2, 1)
5 (1, 5)
6 (1, 6)
7 (1, 7)
8 (2, 2)
9 (3, 1)
10 (1, 10)
11 (1, 11)
12 (2, 3)
13 (1, 13)
14 (1, 14)
15 (1, 15)
16 (4, 1)
17 (1, 17)
18 (3, 2)
19 (1, 19)
20 (2, 5)
21 (1, 21)
22 (1, 22)
23 (1, 23)
24 (2, 6)
25 (5, 1)
26 (1, 26)
27 (3, 3)
28 (2, 7)
29 (1, 29)
30 (1, 30)
31 (1, 31)
32 (4, 2)
33 (1, 33)
34 (1, 34)
35 (1, 35)
36 (6, 1)
</code>```

These are OEIS A000188 and A007913.

Related: A more complex version.

var QUESTION_ID=83814,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/83814/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:
Matlab, 51 bytes

x=input('');y=1:x;z=y(~rem(x,y.^2));a=z(end)
x/a^2

Explanation

x=input('')       -- takes input
y=1:x             -- numbers from 1 to x
z=y(~rem(x,y.^2)) -- numbers such that their squares divide x
a=z(end)          -- biggest such number (first part of output)
x/a^2             -- remaining part


问:
bfcat - encode a file as a brainf*** program

Challenge

Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..

Assume all inputs are encoded as ASCII.

Assume the outputted BF program will execute in an environment with an infinite tape.

Assume the pointer starts at cell 0 with every cell initialized to a value of zero.

Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.

The tape is doubly infinite.

All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.

Examples

Space string

Given the input  , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
++ .
</code>```

Exclamation point

Given the input ! , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++
.
</code>```

Two letters

Given the input hi , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

++++
.
+
.
</code>```

This is code-golf, so the code with the smallest number of bytes wins. Good luck.

答:
Sesos, 12 bytes

Hexdump:

```<code>0000000: 28cbf6 02e83d 655bae 243901                       (....=e[.$9.

Size   : 12 byte(s)
</code>```

Try it online!

Assembler

add 43,fwd 1,get
jmp
  jmp,sub 1,rwd 1,put,fwd 1,jnz
  add 46,put,add 16,put
  get
```

Body:
Sesos, 12 bytes

Hexdump:

0000000: 28cbf6 02e83d 655bae 243901                       (....=e[.$9.

Size   : 12 byte(s)

Try it online!

Assembler

add 43,fwd 1,get
jmp
  jmp,sub 1,rwd 1,put,fwd 1,jnz
  add 46,put,add 16,put
  get


答:
Matlab, 79 bytes

Assuming we can take amt and rate as separate column vectors:

```<code>function[]=f(a,b,c)
t=sort([0;a;c]);fix(sum(diff(t).*[0;b/100].*(t(2:end)<=c)))
</code>```

If we can't (then a is a two-column matrix of amt and rate) it's 87 bytes.

```<code>function[]=f(a,c)
t=sort([0;a(:,1);c]);fix(sum(diff(t).*[0;a(:,2)/100].*(t(2:end)<=c)))
</code>```

Explanation:

```<code>f(a,b,c)           -- takes amt, rate and income
[0;a;c]            -- gives a vector of amounts with 0 and the income amount
t=sort(...)        -- sort this vector
diff(t)            -- gives us amounts to be taxed in every bracket
diff(t).*[0;b/100] -- tax in every bracket
.*(t(2:end)<=c)    -- take only entries lower than the income
sum(...)           -- sum everything
fix(...)           -- round towards 0
</code>```

Title: Build a marginal tax calculator

Body:
There have been some tax rate calculator problems here that depend on defined rates (specifically US federal rates), but none that have done it for arbitrary lists.

Your task is to build a program or function that will take an arbitrary list of marginal tax brackets and calculate the effective amount of tax paid on a given amount of taxable income.

Your program will take as input:

N pairs of numbers in the form (amt, rate), each representing a tax bracket.

amt is the amount of taxable income above which at which the tax rate starts to apply. These amounts will all be integers, and appear in increasing order.

rate is the tax rate, expressed as a decimal percentage from 0 to 100 inclusive.

The amount of taxable income, as a nonnegative integer.

If no rate is specified for $0, the rate is assumed to be 0%.

Alternatively, your program can also take as input two lists (amt1, amt2, ...) and (rate1, rate2, ...), containing the amounts and rates in the same order.

Your program will then output the payable tax, either to two decimal places, or rounded down to the nearest whole currency unit.

An example input (the most recent Canadian tax brackets, from 2016, with the basic personal tax credit applied and nothing else):

```<code>11474 15
45282 20.5
90563 26
140388 29
200000 33

393216
</code>```

And its corresponding output:

```<code>108357.07  or  108357
</code>```

The shortest program in any language to do this wins.

Body:
Matlab, 79 bytes

Assuming we can take amt and rate as separate column vectors:

function[]=f(a,b,c)
t=sort([0;a;c]);fix(sum(diff(t).*[0;b/100].*(t(2:end)<=c)))

If we can't (then a is a two-column matrix of amt and rate) it's 87 bytes.

function[]=f(a,c)
t=sort([0;a(:,1);c]);fix(sum(diff(t).*[0;a(:,2)/100].*(t(2:end)<=c)))

Explanation:

f(a,b,c)           -- takes amt, rate and income
[0;a;c]            -- gives a vector of amounts with 0 and the income amount
t=sort(...)        -- sort this vector
diff(t)            -- gives us amounts to be taxed in every bracket
diff(t).*[0;b/100] -- tax in every bracket
.*(t(2:end)<=c)    -- take only entries lower than the income
sum(...)           -- sum everything
fix(...)           -- round towards 0


答:
C - <s>263</s> <s>247</s> <s>240</s> 238 bytes

This is <s>first</s> <s>second</s> third version, I believe code can be shrinked too.

m[99][99],x,y,a,b,c,n;f(v,w){if(m[v][w]==32){m[v][w]=88;f(v,w+1);f(v+1,w);f(v,w-1);f(v-1,w);}}main(){scanf("%d %d\n",&a,&b);for(;~(c=getchar());m[x++][y]=c,n=x>n?x:n)c==10&&++y&&(x=0);f(b+2,a+1);for(a=-1;++a<y*n+n;)putchar(m[a%n][a/n]);}
```
<p>And readable version:</p>
<pre class="lang-c prettyprint-override"><code>m[99][99], x, y, a, b, c, n;

/*
    a, b - flood fill start coordinates
    v, w - recursive function start coordinates
    x, y - iterators
    c - character read
    m - map
    n - maximum map width found

*/

//Recursive flood function
f( v, w )
{
    if ( m[v][w] == 32 ) //If field is empty (is ' '?)
    {
        m[v][w] = 88; //Put 'X' there
        f(v,w+1);f(v+1,w); //Call itself on neighbour fields
        f(v,w-1);f(v-1,w);
    }
}

main( )
{
    //Read coordinates
    scanf( "%d %d\n", &a, &b );

    //Read map (put character in map, track maximum width)
    for ( ; ~( c = getchar( ) ); m[x++][y] = c, n = x > n ? x : n )
        c == 10 && ++y && ( x = 0 );

    //Flood map
    f( b + 2, a + 1 );

    //Draw
    for ( a = -1; ++a < y * n + n; )
            putchar( m[a % n][a / n] );

}
</code>```

Compile and run:

gcc -o flood floodgolf.c && cat 1.txt | ./flood

Resources:

Input format

Results

Note: I'm working on int values. Every   (32) is treated as empty space. Any other value is treated as border. Coordinates are in format (row, column)

Title: Flood-fill a 2D grid

Body:
Challenge description

Let's call a two-dimentional, rectangular array (meaning its every subarray has the same length), a grid. Every unit of a grid is either an empty space or a border. In a grid of characters, empty space is represented by a single whitespace; any other character is treated as a border. Sample grids (+'s, |'s and -'s added for readability - they are not part of the grid):

```<code>+----+
|    |
|    |
|    |
|    |
|    |
+----+  an empty 4x5 grid

+------+
|      |
|  #   |
|  #   |
+------+  a 6x3 grid with 2 borders

+----------+
|          |
|          |
|  #####   |
|  #   #   |
| ##   # <------ enclosed area
| #    #   |
| ######   |
|          |
+----------+  a 10x8 grid with an enclosed area
</code>```

Given a 2D grid and a pair of coordinates, fill the enclosed area surrounding the point represented by the coordinates.

Sample inputs / outputs

1)

```<code>0 0
+----------+      +----------+
|          |      |XXXXXXXXXX|
|          |  ->  |XXXXXXXXXX|
|          |      |XXXXXXXXXX|
+----------+      +----------+
</code>```

2)

```<code>6 5
+-----------------+      +-----------------+
|                 |      |                 |
|                 |      |                 |
|    ########     |      |    ########     |
|    #       #    |      |    #XXXXXXX#    |
|    #    ####    |      |    #XXXX####    |
|    #    #       |      |    #XXXX#       |
|    #    #       |  ->  |    #XXXX#       |
|    #    #       |      |    #XXXX#       |
|     ####        |      |     ####        |
|                 |      |                 |
|                 |      |                 |
+-----------------+      +-----------------+
</code>```

3)

```<code>4 6
+-----------------+      +-----------------+
|                 |      |XXXXXXXXXXXXXXXXX|
|    ####         |      |XXXX####XXXXXXXXX|
|   #    #        |  ->  |XXX#    #XXXXXXXX|
|    ####         |      |XXXX####XXXXXXXXX|
|                 |      |XXXXXXXXXXXXXXXXX|
+-----------------+      +-----------------+
</code>```

4)

```<code>4 5
+-----------------+      +-----------------+      +-----------------+
|                 |      |                 |      |                 |
|                 |      |                 |      |                 |
|    ####         |      |    ####         |      |     XXXX        |
|    ####         |  ->  |    ####         |  or  |     XXXX        |
|    ####         |      |    ####         |      |     XXXX        |
|                 |      |                 |      |                 |
+-----------------+      +-----------------+      +-----------------+
</code>```

5)

```<code>2 6
+----------------+      +----------------+
|                |      |XXXXXXXXXXXXXXXX|
|                |      |XXXXXXXXXXXXXXXX|
|                |      |XXXXXXXXXXXXXXXX|
|                |  ->  |XXXXXXXXXXXXXXXX|
|                |      |XXXXXXXXXXXXXXXX|
|BBBBBBBBBBBBBBBB|      |BBBBBBBBBBBBBBBB|
|                |      |                |
|                |      |                |
+----------------+      +----------------+
</code>```

Notes

An empty grid is considered enclosed, i.e. borders are implicitly situated along the edges of the grid as well (see examples 1. and 5.),

A corner of an enclosed area doesn't need to be L-shaped. The following two areas are therefore equivalent:

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

If a unit under the coordinates happens to be a border you can either leave the grid unchanged (as in example 4.) or treat it as an empty space,

You can choose any character for filler / empty space as long as you include this information in the submission,

If using a type other than char suits your purposes better, you can use ints (0 for empty space, 1 for border) or booleans (true and false respectively) or any other type - just make sure to include this information in your submission,

Coordinates used in the examples above are 0-indexed (row, column) coordinates, as it's more convenient for two-dimensional array. If you want to use (column, row) (cartesian) system and/or non-0-indexed coordinates, specify it in your submission.

If you don't know where to start, check out Wikipedia article on flood fill

Remember that this is a code-golf challenge, so make your code as short as possible!

Body:
C - <s>263</s> <s>247</s> <s>240</s> 238 bytes

This is <s>first</s> <s>second</s> third version, I believe code can be shrinked too.

m[99][99],x,y,a,b,c,n;f(v,w){if(m[v][w]==32){m[v][w]=88;f(v,w+1);f(v+1,w);f(v,w-1);f(v-1,w);}}main(){scanf("%d %d\n",&a,&b);for(;~(c=getchar());m[x++][y]=c,n=x>n?x:n)c==10&&++y&&(x=0);f(b+2,a+1);for(a=-1;++a<y*n+n;)putchar(m[a%n][a/n]);}

And readable version:

m[99][99], x, y, a, b, c, n;

/*
    a, b - flood fill start coordinates
    v, w - recursive function start coordinates
    x, y - iterators
    c - character read
    m - map
    n - maximum map width found

*/

//Recursive flood function
f( v, w )
{
    if ( m[v][w] == 32 ) //If field is empty (is ' '?)
    {
        m[v][w] = 88; //Put 'X' there
        f(v,w+1);f(v+1,w); //Call itself on neighbour fields
        f(v,w-1);f(v-1,w);
    }
}

main( )
{
    //Read coordinates
    scanf( "%d %d\n", &a, &b );

    //Read map (put character in map, track maximum width)
    for ( ; ~( c = getchar( ) ); m[x++][y] = c, n = x > n ? x : n )
        c == 10 && ++y && ( x = 0 );

    //Flood map
    f( b + 2, a + 1 );

    //Draw
    for ( a = -1; ++a < y * n + n; )
            putchar( m[a % n][a / n] );

}

Compile and run:

gcc -o flood floodgolf.c && cat 1.txt | ./flood

Resources:

Input format

Results

Note: I'm working on int values. Every   (32) is treated as empty space. Any other value is treated as border. Coordinates are in format (row, column)


答:
Mathematica 34 bytes

```<code>#/.{a_ b_^_:>{a, b},_[b_,_]:>{1,b}}&
</code>```

This says to replace all the input (#) according to the following rules:
(1) a number, a,  times the square root of b should be replaced by {a, b}  and a function b to the power of whatever should be replaced by {1,b}
.  Note that the function assumes that the input will be of the form, Sqrt[n].
It will not work with other sorts of input.

This unnamed function is unusually cryptic for Mathematica. It can be clarified somewhat by showing its full form, followed by replacements of the original shorter forms.

```<code>Function[
   ReplaceAll[
      Slot[1],
      List[
         RuleDelayed[Times[Pattern[a,Blank[]],Power[Pattern[b,Blank[]],Blank[]]],List[a,b]],
         RuleDelayed[Blank[][Pattern[b,Blank[]],Blank[]],List[1,b]]]]]
</code>```

which is the same as

```<code>   ReplaceAll[
      #,
      List[
         RuleDelayed[Times[Pattern[a,Blank[]],Power[Pattern[b,Blank[]],Blank[]]],List[a,b]],
         RuleDelayed[Blank[][Pattern[b,Blank[]],Blank[]],List[1,b]]]]&
</code>```

and

```<code>ReplaceAll[#,
  List[RuleDelayed[
    Times[Pattern[a, Blank[]],
     Power[Pattern[b, Blank[]], Blank[]]], {a, b}],
   RuleDelayed[Blank[][Pattern[b, Blank[]], Blank[]], {1, b}]]] &
</code>```

and

```<code>ReplaceAll[#,
  List[RuleDelayed[Times[a_, Power[b_, _]], {a, b}],
   RuleDelayed[Blank[][b_, _], {1, b}]]] &
</code>```

and

```<code>ReplaceAll[#, {RuleDelayed[a_*b^_, {a, b}], RuleDelayed[_[b_, _], {1, b}]}]&
</code>```

and

```<code>ReplaceAll[#, {a_*b^_ :> {a, b}, _[b_, _] :> {1, b}}] &
</code>```

Title: Simplify a square root

Body:
Mathematica 34 bytes

#/.{a_ b_^_:>{a, b},_[b_,_]:>{1,b}}&

This says to replace all the input (#) according to the following rules:
(1) a number, a,  times the square root of b should be replaced by {a, b}  and a function b to the power of whatever should be replaced by {1,b}
.  Note that the function assumes that the input will be of the form, Sqrt[n].
It will not work with other sorts of input.

This unnamed function is unusually cryptic for Mathematica. It can be clarified somewhat by showing its full form, followed by replacements of the original shorter forms.

Function[
   ReplaceAll[
      Slot[1],
      List[
         RuleDelayed[Times[Pattern[a,Blank[]],Power[Pattern[b,Blank[]],Blank[]]],List[a,b]],
         RuleDelayed[Blank[][Pattern[b,Blank[]],Blank[]],List[1,b]]]]]

which is the same as

   ReplaceAll[
      #,
      List[
         RuleDelayed[Times[Pattern[a,Blank[]],Power[Pattern[b,Blank[]],Blank[]]],List[a,b]],
         RuleDelayed[Blank[][Pattern[b,Blank[]],Blank[]],List[1,b]]]]&

and

ReplaceAll[#,
  List[RuleDelayed[
    Times[Pattern[a, Blank[]],
     Power[Pattern[b, Blank[]], Blank[]]], {a, b}],
   RuleDelayed[Blank[][Pattern[b, Blank[]], Blank[]], {1, b}]]] &

and

ReplaceAll[#,
  List[RuleDelayed[Times[a_, Power[b_, _]], {a, b}],
   RuleDelayed[Blank[][b_, _], {1, b}]]] &

and

ReplaceAll[#, {RuleDelayed[a_*b^_, {a, b}], RuleDelayed[_[b_, _], {1, b}]}]&

and

ReplaceAll[#, {a_*b^_ :> {a, b}, _[b_, _] :> {1, b}}] &


Title: bfcat - encode a file as a brainf*** program

Body:
Challenge

Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..

Assume all inputs are encoded as ASCII.

Assume the outputted BF program will execute in an environment with an infinite tape.

Assume the pointer starts at cell 0 with every cell initialized to a value of zero.

Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.

The tape is doubly infinite.

All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.

Examples

Space string

Given the input  , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
++ .
</code>```

Exclamation point

Given the input ! , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++
.
</code>```

Two letters

Given the input hi , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

++++
.
+
.
</code>```

This is code-golf, so the code with the smallest number of bytes wins. Good luck.

Body:
Jelly, 8 bytes

O”+ẋp“.>

Try it online!

Sample run

For input hi, this program prints

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++>

(without the linefeeds) which, in turn, <a href="http://brainfuck.tryitonline.net/#code=KysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysuKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKys-KysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrLisrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKz4&input=" rel="noreferrer">prints hi.

How it works

O”+ẋp“.>  Main link. Argument: s (string)

O         Ordinal; convert each character in s into its code point.
 ”+       Yield the character '+'.
   ẋ      Repeat '+' k times, for each k in the code points.
     “.>  Yield the string ".>".
    p     Take the Cartesian product of both results.


答:
C, 162 bytes

w,l;char*d;f(z){z<0||z>l||d[z]^32||++d[z]&&f(z+1)+f(z-1)+f(z+w)+f(z-w);}main(c,v)char**v;{l=strlen(d=v[3]),w=strchr(d,10)-d+1,f(atoi(v[2])*w+atoi(v[1]));puts(d);}
```

<p>Takes input from arguments (<code>./floodfill X Y grid</code>). Grid must contain <code>\n</code> or <code>\r\n</code> between each line, final newline is optional. Simplest way I've found to invoke from shell:</p>

```./floodfill 1 0 "$(printf "   \n###\n   \n")"
# or
./floodfill 1 0 "$(cat gridfile)"
```

<p>Outputs to stdout, using <code>!</code> for the fill character. If the start position coincides with a <code>#</code>, makes no change.</p>

<h3>Breakdown:</h3>

<pre class="lang-c prettyprint-override"><code>                                    // GCC is happy enough without any imports
w,l;                                // Globals (line width, total length)
char*d;                             // Global grid pointer
f(z){                               // "Fill" function - z=current cell
    z<0||z>l||                      // Check if out-of-bounds...
    d[z]^32||                       // ...or not empty
        ++d[z]&&                    // Fill cell...
        f(z+1)+f(z-1)+f(z+w)+f(z-w);// ...and continue in "+" pattern
}
main(c,v)char**v;{                  // K&R style function to save 2 bytes
    l=strlen(d=v[3]),               // Store grid & length
    w=strchr(d,10)-d+1,             // Store width of grid (including newlines)
    f(atoi(v[2])*w+atoi(v[1]));     // Parse X & Y arguments and invoke fill

    puts(d);}                       // Print the result
</code>```

Note that this relies on modifying the input argument string, which is forbidden, so this may not work on all platforms (implicit declarations also make this non-standard).

Title: Flood-fill a 2D grid

Body:
C, 162 bytes

w,l;char*d;f(z){z<0||z>l||d[z]^32||++d[z]&&f(z+1)+f(z-1)+f(z+w)+f(z-w);}main(c,v)char**v;{l=strlen(d=v[3]),w=strchr(d,10)-d+1,f(atoi(v[2])*w+atoi(v[1]));puts(d);}

Takes input from arguments (./floodfill X Y grid). Grid must contain \n or \r\n between each line, final newline is optional. Simplest way I've found to invoke from shell:

./floodfill 1 0 "$(printf "   \n###\n   \n")"
# or
./floodfill 1 0 "$(cat gridfile)"

Outputs to stdout, using ! for the fill character. If the start position coincides with a #, makes no change.

Breakdown:

                                    // GCC is happy enough without any imports
w,l;                                // Globals (line width, total length)
char*d;                             // Global grid pointer
f(z){                               // "Fill" function - z=current cell
    z<0||z>l||                      // Check if out-of-bounds...
    d[z]^32||                       // ...or not empty
        ++d[z]&&                    // Fill cell...
        f(z+1)+f(z-1)+f(z+w)+f(z-w);// ...and continue in "+" pattern
}
main(c,v)char**v;{                  // K&R style function to save 2 bytes
    l=strlen(d=v[3]),               // Store grid & length
    w=strchr(d,10)-d+1,             // Store width of grid (including newlines)
    f(atoi(v[2])*w+atoi(v[1]));     // Parse X & Y arguments and invoke fill

    puts(d);}                       // Print the result

Note that this relies on modifying the input argument string, which is forbidden, so this may not work on all platforms (implicit declarations also make this non-standard).


问:
Given a number, program must return the alphabet letter correspondent

The program

Given a number, program must return the alphabet letter correspondent.

Rules

The challenge here is to make it as short as possible, everyone knows it is a very easy program to do.

The number is not zero-based, it means 1 is A, 2 is B, 3 is C and so it goes...

Any language will be accepted.

Body:
PHP 442

$alphabet = Array('A' => 1,'B' => 2,'C' => 3,'D' => 4,'E' => 5,'F' => 6,'G' => 7,'H' => 8,
'I' => 9,'J' => 10,'K' => 11,'L' => 12,'M' => 13,'N' => 14,'O' => 15,'P' => 16,'Q' => 17,
'R' => 18,'S' => 19,'T' => 20,'U' => 21,'V' => 22,'W' => 23,'X' => 24,'Y' => 25,'Z' => 26
)

function testInputForAlphabetCharacter($input){
    for($index = 0; $index < count($alphabet); $i = $i + 1){
        if($alphabet[$index] == $input){
            echo($index);
        }
    }
}

$input = $_GET['input'];
testInputForAlphabetCharacter($input);


答:
Pyth - 11 bytes

```<code>sm+*\+Cd".>
</code>```

Try it online here.

Body:
Pyth - 11 bytes

sm+*\+Cd".>

Try it online here.


答:
Brainfuck, <s>55</s> 51 bytes

```<code>,[>+++[>+++++++<-]>[<++>>+++<-]<+<[>.<-]>+++.>>-.,]
</code>```

Try it online!

Example output for hi (without the linefeeds):

```<code>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>
</code>```

Explanation

This moves across the tape while writing the program. The surrounding ,[...,] is a standard input loop. For each character, we use four cells:

```<code>[... x a b c ...]
</code>```

where x is the cell we write the input to.

```<code>>+++[>+++++++<-]
</code>```

This part uses cell a to write a 21 into cell b via a standard multiplication of 3 and 7.

```<code>>[<++>>+++<-]
</code>```

Now we use that 21 to write 42 into a and 63 into c by multiplying by 2 and 3 respectively. Then <+< moves back to cell x while turning the 42 into a 43 (the code point of +). Recap:

```<code>[... x 43 21 63 ...]
</code>```

Now the main output loop:

```<code>[>.<-]
</code>```

That is, while decrementing x we print one + each time.

```<code>>+++.
</code>```

After we're done we reuse the + cell, by adding 3 to give ..

```<code>>>-.
</code>```

Finally, we move to the 63, decrement it to 62 (>) and output that as well. The next iteration will use this cell as x.

Body:
Brainfuck, <s>55</s> 51 bytes

,[>+++[>+++++++<-]>[<++>>+++<-]<+<[>.<-]>+++.>>-.,]

Try it online!

Example output for hi (without the linefeeds):

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>

Explanation

This moves across the tape while writing the program. The surrounding ,[...,] is a standard input loop. For each character, we use four cells:

[... x a b c ...]

where x is the cell we write the input to.

>+++[>+++++++<-]

This part uses cell a to write a 21 into cell b via a standard multiplication of 3 and 7.

>[<++>>+++<-]

Now we use that 21 to write 42 into a and 63 into c by multiplying by 2 and 3 respectively. Then <+< moves back to cell x while turning the 42 into a 43 (the code point of +). Recap:

[... x 43 21 63 ...]

Now the main output loop:

[>.<-]

That is, while decrementing x we print one + each time.

>+++.

After we're done we reuse the + cell, by adding 3 to give ..

>>-.

Finally, we move to the 63, decrement it to 62 (>) and output that as well. The next iteration will use this cell as x.


答:
JavaScript (ECMAScript 2016), 40 bytes

```<code>n=>{for(k=n;n%k**2;k--);return[k,n/k/k]}
</code>```

Basically a JavaScript port of Dennis's Python 2 answer.

Try it on JSBin.

Note: it doesn't work in strict mode, because k is not initialized anywhere. To make it work in strict mode, k=n in the loop should be changed to let k=n.

Title: Simplify a square root

Body:
JavaScript (ECMAScript 2016), 40 bytes

n=>{for(k=n;n%k**2;k--);return[k,n/k/k]}

Basically a JavaScript port of Dennis's Python 2 answer.

Try it on JSBin.

Note: it doesn't work in strict mode, because k is not initialized anywhere. To make it work in strict mode, k=n in the loop should be changed to let k=n.


问:
Exploded substrings

Introduction

Let's observe the string abc. The substrings that can be made from this are:

```<code>a, ab, abc, b, bc, c
</code>```

We now need to align them under the initial string, like this:

```<code>abc
a
 b
  c
ab
 bc
abc
</code>```

The order of the string doesn't matter, so this is also perfectly valid:

```<code>abc
a
ab
abc
 b
 bc
  c
</code>```

So, the substring is positioned under the location of the substring in the initial string. So for abcdef and the substring cde, it would look like this:

```<code>abcdef
  cde
</code>```

The Task

The task is to align all substrings with a length greater than 0, like shown above. You can assume that the string itself will only contain alphabetic characters and has at least 1 character. For the padding, you can use a space or some other non-alphabetic printable ASCII character (32 - 127). Maybe not necessary to mention, but the string itself will only contain unique characters, so not like aba, since the a occurs twice.

Test cases

Input: abcde

Possible output:

```<code>a
ab
abc
abcd
abcde
 b
 bc
 bcd
 bcde
  c
  cd
  cde
   d
   de
    e
</code>```

Input: abcdefghij

Possible output:

```<code>a
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
abcdefghij
 b
 bc
 bcd
 bcde
 bcdef
 bcdefg
 bcdefgh
 bcdefghi
 bcdefghij
  c
  cd
  cde
  cdef
  cdefg
  cdefgh
  cdefghi
  cdefghij
   d
   de
   def
   defg
   defgh
   defghi
   defghij
    e
    ef
    efg
    efgh
    efghi
    efghij
     f
     fg
     fgh
     fghi
     fghij
      g
      gh
      ghi
      ghij
       h
       hi
       hij
        i
        ij
         j
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

答:
Java, 138 bytes

String e(String s){int l=s.length(),a=0,i,j;for(;++a<l;)for(i=0;i<=l-a;){s+="\n";for(j=0;j++<i;)s+=" ";s+=s.substring(i,i+++a);}return s;}
```

<p>Formatted:</p>

<pre class="lang-java prettyprint-override"><code>String e(String s) {
    int l = s.length(), a = 0, i, j;
    for (; ++a < l;)
        for (i = 0; i <= l - a;) {
            s += "\n";
            for (j = 0; j++ < i;)
                s += " ";
            s += s.substring(i, i++ + a);
        }
    return s;
}
</code>```

Title: Exploded substrings

Body:
Java, 138 bytes

String e(String s){int l=s.length(),a=0,i,j;for(;++a<l;)for(i=0;i<=l-a;){s+="\n";for(j=0;j++<i;)s+=" ";s+=s.substring(i,i+++a);}return s;}

Formatted:

String e(String s) {
    int l = s.length(), a = 0, i, j;
    for (; ++a < l;)
        for (i = 0; i <= l - a;) {
            s += "\n";
            for (j = 0; j++ < i;)
                s += " ";
            s += s.substring(i, i++ + a);
        }
    return s;
}


答:
Vitsy, <s>19</s> 17 bytes

```<code>I\[&'>.+'i1-\Du]Z

I                     Get the length of the input stack.
 \[            ]      Pop n, repeat this block of code n times.
   &                  Push a new stack and move to it.
    '>.+'             Push the string '+.>' to the stack.
         i            Pop an item from the input stack and push it to the current
                      program stack.
          1-          Subtract one from the top program stack item.
            \D        Duplicate the '+' in the stack that many times.
              u       Merge the current program stack with the previous.
                Z     Output the entire current stack as a string.
</code>```

Note that this answer is one of the few times that I've ever used I and u. :D

Try it online!

Body:
Vitsy, <s>19</s> 17 bytes

I\[&'>.+'i1-\Du]Z

I                     Get the length of the input stack.
 \[            ]      Pop n, repeat this block of code n times.
   &                  Push a new stack and move to it.
    '>.+'             Push the string '+.>' to the stack.
         i            Pop an item from the input stack and push it to the current
                      program stack.
          1-          Subtract one from the top program stack item.
            \D        Duplicate the '+' in the stack that many times.
              u       Merge the current program stack with the previous.
                Z     Output the entire current stack as a string.

Note that this answer is one of the few times that I've ever used I and u. :D

Try it online!


问:
Print your code backwards - reverse quine
Write a program that prints its own source code out backwards, in other words an eniuq.

Scoring:

+50 if you use pull data from the Internet.

+25 if you read your own source code.

+1 point per character

Lowest score wins.

Rules:

No using other files (e.g. reverse.txt)

Minimum code length is two characters.

Your program cannot be a palindrome.

答:
Fuzzy Octo Guacamole, 4 bytes

```<code>KNU_
</code>```

K prints _UNK, N pushes None, and U pushes 0. And _ pops the top value on the stack (but doesn't print). So only _UNK is printed.

Body:
Fuzzy Octo Guacamole, 4 bytes

KNU_

K prints _UNK, N pushes None, and U pushes 0. And _ pops the top value on the stack (but doesn't print). So only _UNK is printed.


答:
Javascript, 25 chars

```<code>String.fromCharCode(66-x);
</code>```

PHP, 22 chars

```<code>echo chr(66-$argv[0])
</code>```

Body:
The program

Given a number, program must return the alphabet letter correspondent.

Rules

The challenge here is to make it as short as possible, everyone knows it is a very easy program to do.

The number is not zero-based, it means 1 is A, 2 is B, 3 is C and so it goes...

Any language will be accepted.

Body:
Javascript, 25 chars

String.fromCharCode(66-x);

PHP, 22 chars

echo chr(66-$argv[0])


答:
K6, 16 bytes

```<code>,/{|">.",x#"+"}'
</code>```

Usage

```<code>,/{|">.",x#"+"}'"some string"
</code>```

Explanation

```<code>  {           }'  For each character in the string...
         x#"+"    Repeat "+" as many times as the character's ASCII code.
        ,         Combine that with...
    ">."          The code to print it and move on.
   |              But we put the string together backwards...so now it gets reversed.
,/                Combine all the substrings into one BIG string.
</code>```

Body:
K6, 16 bytes

,/{|">.",x#"+"}'

Usage

,/{|">.",x#"+"}'"some string"

Explanation

  {           }'  For each character in the string...
         x#"+"    Repeat "+" as many times as the character's ASCII code.
        ,         Combine that with...
    ">."          The code to print it and move on.
   |              But we put the string together backwards...so now it gets reversed.
,/                Combine all the substrings into one BIG string.


答:
O, 13 bytes

```<code>i{'+n#*".>"}d
</code>```

Explanation:

```<code>i              Read standard input into a string and push it onto the stack.
 {         }d  For each character in the string...
  '+           Push "+".
    n#         Convert the character (n) to its ASCII code.
      *        Multiply the "+" by the character code to get the number of +'s needed.
       ".>"    Push the string ".>".
               In O, the stack is printed after execution, so this prints out the result.
</code>```

Body:
O, 13 bytes

i{'+n#*".>"}d

Explanation:

i              Read standard input into a string and push it onto the stack.
 {         }d  For each character in the string...
  '+           Push "+".
    n#         Convert the character (n) to its ASCII code.
      *        Multiply the "+" by the character code to get the number of +'s needed.
       ".>"    Push the string ".>".
               In O, the stack is printed after execution, so this prints out the result.


答:
05AB1E, <s>12</s> 11 bytes

```<code>vyÇ`'+×„.>J
</code>```

Explained

```<code>v             # for each char in input string
 yÇ`          # convert to its ascii value
    '+×       # push the char '+' that many times
       „.>J   # push string ".>" and join with the plus signs
              # implicitly print combined string
</code>```

Try it online

Saved 1 byte thanks to @Adnan

Body:
05AB1E, <s>12</s> 11 bytes

vyÇ`'+×„.>J

Explained

v             # for each char in input string
 yÇ`          # convert to its ascii value
    '+×       # push the char '+' that many times
       „.>J   # push string ".>" and join with the plus signs
              # implicitly print combined string

Try it online

Saved 1 byte thanks to @Adnan


问:
Evaluate a Stratego Battle
In the game Stratego, the main game mechanic is when you attack an opponent's piece with yours. In this challenge, you job is to simulate one of these battles and say who survives.

Specs

You will get as input a pair of string representing Stratego pieces. The pieces are one of "S 1 2 3 4 5 6 7 8 9 10 B" (S is the Spy, and B are bombs). The first of the pair will be the attacker, and the second the attacked.

Here are the rules for determining the results of a battle:

The higher number beats the lower number: ["4", "6"] -> ["6"].

If both are the same, then both die: ["7", "7"] -> [].

Spies are at the bottom, underneath even 1: ["S", "2"] -> ["2"].

However, if a spy attacks the 10, then the spy wins: ["S", "10"] -> ["S"].

But the normal rules still apply if the 10 is the one attacking: ["10", "S"] -> ["10"].

If anything attacks a bomb, the bomb wins: ["5", "B"] -> ["B"].

However, a miner (a 3), can defuse a bomb: ["3", "B"] -> ["3"].

A bomb will never be the attacker.

A spotter (a 1), can attack using the normal mechanism, but they can also try to "guess" the rank of the other player, which can be denoted with any sane notation.

If they guess correctly, the other piece dies: ["1(5)", "5"] -> ["1"].

If they guess wrong, nothing happens: ["1(3)", "5"] -> ["1", "5"].

Spotters can spot bombs: ["1(B)", "B"] -> ["1"].

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

(You can use the examples up there as test-cases, because I'm too lazy to put them all together in one list).

答:
Python, <s>180</s> 153 bytes

```<code>def f(a,d,g=0):T=([[d]],[[a]]);return([[a]+[d]*(g!=d)]*(g!=0)+[[]]*(a==d)+T[d=="10"]*(a=="S")+T[1]*(d=="S")+T[a=="3"]*(d=="B")+T[int(a,36)>int(d,36)])[0]
</code>```

The function takes the attacker, defender and optionally the spotter's guess (if the attacker is the spotter) as arguments.  It returns an array containing the live pieces that remain.

Ungolfed

```<code>def f(a,d,g=0):
 if g: return [a] if g==d else [a,d]
 if a==d: return []
 if a=="S": return [a] if d=="10" else [d]
 if d=="S": return[a]
 if d=="B": return [a] if a=="3" else [d]
 return [a] if int(a)>int(d) else [d]
</code>```

Demo

https://repl.it/C6Oz/2

Title: Evaluate a Stratego Battle

Body:
Python, <s>180</s> 153 bytes

def f(a,d,g=0):T=([[d]],[[a]]);return([[a]+[d]*(g!=d)]*(g!=0)+[[]]*(a==d)+T[d=="10"]*(a=="S")+T[1]*(d=="S")+T[a=="3"]*(d=="B")+T[int(a,36)>int(d,36)])[0]

The function takes the attacker, defender and optionally the spotter's guess (if the attacker is the spotter) as arguments.  It returns an array containing the live pieces that remain.

Ungolfed

def f(a,d,g=0):
 if g: return [a] if g==d else [a,d]
 if a==d: return []
 if a=="S": return [a] if d=="10" else [d]
 if d=="S": return[a]
 if d=="B": return [a] if a=="3" else [d]
 return [a] if int(a)>int(d) else [d]

Demo

https://repl.it/C6Oz/2


答:
Javascript, <s>179</s> <s>166</s> 160 bytes

f=(a,c,b,n="")=>{if(c)if(c==b)return[a];else return[a,b];if(a==b)return[];a+b=="3B"&&(b=n);a=b=="B"?n:a;b=b=="S"?n:b;a+b=="S10"&&(a=n,b="S");return[+a>+b?a:b]}
```

<p>This function takes 3 arguments - first one is attacker, second is used for spotters (their guess) and third is defender.</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f = ( a, c, b, n = "" ) =>
{
 //Takes attacker (a), guess (c) and defender (b), n is only declaration
 //c should never be set unless a == 1
 if ( c )
  if ( c == b ) return [ a ];
  else return[ a, b ]; //Spotters

 if( a == b ) return [ ]; //Kill each other if same

 a + b == "3B" && ( b = n ); //Miners destroy bombs
 a = b == "B" ? n : a; //Bomb kills almost everything
 b = b == "S" ? n : b; //Spy dies if anything attacks him
 a + b == "S10" && ( a = n, b = "S" ); //Spies kill 10s

 console.log( JSON.stringify( [a,b] ) );

 return [ +a > +b ? a : b ] //Higher number wins
}

function fight( )
{
 var input = [ [ attacker.value, guess.value], defender.value ];
 out.innerHTML += JSON.stringify( input ) + "   ->   " + JSON.stringify( f( input[0][0], input[0][1], input[1] ) ) + "<br>";
}</code>```

#sword
{
 width: 40px;
 height: auto;
 margin: 10px;
 cursor: pointer;

}

#guess
{
 width: 40px;
}

textarea
{
 height: 20px;
 margin-top: 0px;
}

.panel
{
 background-color: #DDDDDD;
 padding: 5px;
 border: 3px solid black;
}

#out
{
 border: 3px solid black;
 font-family: monospace;
 padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
 <tr>
  <td class=panel>
   <textarea id=attacker placeholder="Attacker"></textarea>
   <textarea id=guess></textarea>
  </td>

  <td>
   <img onclick="fight()" id=sword src="http://cliparts.co/cliparts/8cx/Kjq/8cxKjqAKi.png"></img>
  </td>

  <td class=panel>
   <textarea id=defender placeholder="Defender"></textarea>
  </td>
 </tr>

 <tr>
  <td colspan=3>
   <div id=out></div>
  </td>
 </tr>
</table></code>```

Sword icon comes from cliparts.co

Title: Evaluate a Stratego Battle

Body:
In the game Stratego, the main game mechanic is when you attack an opponent's piece with yours. In this challenge, you job is to simulate one of these battles and say who survives.

Specs

You will get as input a pair of string representing Stratego pieces. The pieces are one of "S 1 2 3 4 5 6 7 8 9 10 B" (S is the Spy, and B are bombs). The first of the pair will be the attacker, and the second the attacked.

Here are the rules for determining the results of a battle:

The higher number beats the lower number: ["4", "6"] -> ["6"].

If both are the same, then both die: ["7", "7"] -> [].

Spies are at the bottom, underneath even 1: ["S", "2"] -> ["2"].

However, if a spy attacks the 10, then the spy wins: ["S", "10"] -> ["S"].

But the normal rules still apply if the 10 is the one attacking: ["10", "S"] -> ["10"].

If anything attacks a bomb, the bomb wins: ["5", "B"] -> ["B"].

However, a miner (a 3), can defuse a bomb: ["3", "B"] -> ["3"].

A bomb will never be the attacker.

A spotter (a 1), can attack using the normal mechanism, but they can also try to "guess" the rank of the other player, which can be denoted with any sane notation.

If they guess correctly, the other piece dies: ["1(5)", "5"] -> ["1"].

If they guess wrong, nothing happens: ["1(3)", "5"] -> ["1", "5"].

Spotters can spot bombs: ["1(B)", "B"] -> ["1"].

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

(You can use the examples up there as test-cases, because I'm too lazy to put them all together in one list).

Body:
Javascript, <s>179</s> <s>166</s> 160 bytes

f=(a,c,b,n="")=>{if(c)if(c==b)return[a];else return[a,b];if(a==b)return[];a+b=="3B"&&(b=n);a=b=="B"?n:a;b=b=="S"?n:b;a+b=="S10"&&(a=n,b="S");return[+a>+b?a:b]}

This function takes 3 arguments - first one is attacker, second is used for spotters (their guess) and third is defender.

f = ( a, c, b, n = "" ) =>
{
 //Takes attacker (a), guess (c) and defender (b), n is only declaration
 //c should never be set unless a == 1
 if ( c )
  if ( c == b ) return [ a ];
  else return[ a, b ]; //Spotters

 if( a == b ) return [ ]; //Kill each other if same

 a + b == "3B" && ( b = n ); //Miners destroy bombs
 a = b == "B" ? n : a; //Bomb kills almost everything
 b = b == "S" ? n : b; //Spy dies if anything attacks him
 a + b == "S10" && ( a = n, b = "S" ); //Spies kill 10s

 console.log( JSON.stringify( [a,b] ) );

 return [ +a > +b ? a : b ] //Higher number wins
}

function fight( )
{
 var input = [ [ attacker.value, guess.value], defender.value ];
 out.innerHTML += JSON.stringify( input ) + "   ->   " + JSON.stringify( f( input[0][0], input[0][1], input[1] ) ) + "<br>";
}

#sword
{
 width: 40px;
 height: auto;
 margin: 10px;
 cursor: pointer;

}

#guess
{
 width: 40px;
}

textarea
{
 height: 20px;
 margin-top: 0px;
}

.panel
{
 background-color: #DDDDDD;
 padding: 5px;
 border: 3px solid black;
}

#out
{
 border: 3px solid black;
 font-family: monospace;
 padding: 10px;
}

<table>
 <tr>
  <td class=panel>
   <textarea id=attacker placeholder="Attacker"></textarea>
   <textarea id=guess></textarea>
  </td>

  <td>
   <img onclick="fight()" id=sword src="http://cliparts.co/cliparts/8cx/Kjq/8cxKjqAKi.png"></img>
  </td>

  <td class=panel>
   <textarea id=defender placeholder="Defender"></textarea>
  </td>
 </tr>

 <tr>
  <td colspan=3>
   <div id=out></div>
  </td>
 </tr>
</table>

Sword icon comes from cliparts.co


答:
Java, 98 bytes

```<code>class a{String A(char[]b){String z="";for(char B:b){for(int c=B;c-->0;)z+="+";z+=".>";}return z;}}
</code>```

Strings are nothing more than immutable char[]s with a bunch of utility methods, so let's use the array!

Ungolfed:

```<code>class a {
    void A(char[] b) {
        for (char B : b) {
            for (int c = B; c-- > 0;)
                 System.out.print('+');
            System.out.print(".>");
        }
    }
}
</code>```

Equivalent standalone program that is 138 bytes long:

```<code>interface a{static void main(String[]A){for(char b:A[0].toCharArray()){for(int B=b;B-->0;)System.out.print('+');System.out.print(".>");}}}
</code>```

Bonus:

```<code>interface a{static void main(String[]A){for(char b:new java.util.Scanner(new java.io.File(A[0])).useDelimiter("\\Z").next().toCharArray()){for(int B=b;B>0;B--)System.out.print('+');System.out.print(".>");}}}
</code>```

This 207-byte app actually encodes a file as a BF program, just as said in the title.

Body:
Challenge

Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..

Assume all inputs are encoded as ASCII.

Assume the outputted BF program will execute in an environment with an infinite tape.

Assume the pointer starts at cell 0 with every cell initialized to a value of zero.

Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.

The tape is doubly infinite.

All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.

Examples

Space string

Given the input  , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
++ .
</code>```

Exclamation point

Given the input ! , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++
.
</code>```

Two letters

Given the input hi , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

++++
.
+
.
</code>```

This is code-golf, so the code with the smallest number of bytes wins. Good luck.

Body:
Java, 98 bytes

class a{String A(char[]b){String z="";for(char B:b){for(int c=B;c-->0;)z+="+";z+=".>";}return z;}}

Strings are nothing more than immutable char[]s with a bunch of utility methods, so let's use the array!

Ungolfed:

class a {
    void A(char[] b) {
        for (char B : b) {
            for (int c = B; c-- > 0;)
                 System.out.print('+');
            System.out.print(".>");
        }
    }
}

Equivalent standalone program that is 138 bytes long:

interface a{static void main(String[]A){for(char b:A[0].toCharArray()){for(int B=b;B-->0;)System.out.print('+');System.out.print(".>");}}}

Bonus:

interface a{static void main(String[]A){for(char b:new java.util.Scanner(new java.io.File(A[0])).useDelimiter("\\Z").next().toCharArray()){for(int B=b;B>0;B--)System.out.print('+');System.out.print(".>");}}}

This 207-byte app actually encodes a file as a BF program, just as said in the title.