答:
Logo, <s>232 207 196</s> 190 bytes

Did somebody say triangles?

Get out your compass and protractor, and let's do this the graphical way.  The geometry uses an equilateral triangle to align the results.  I previously had an isosceles triangle, but it involved too many decimal places.  This change also compacted the output, reducing the amount of screen prep and font changing I had to do.

I used the Calormen online interpreter to flesh this one out.  If you don't have enough screen real estate, it's going to wrap, but you can also fiddle with some numbers to take care of that.  I used the "F11" full-screen mode on my browser.

```<code>ht
pu
to r:n:b:l repeat:n[rt:b label char 90-:n lt:b fd:l] end
to t:s
fd 12 rt 120 bk 6
repeat 2[r:s 90 12]
repeat 2[rt 120 r:s 90-heading 24]
end
rt 90 label "Z lt 210
repeat 25[t repcount]
</code>```

The r procedure draws a line of n characters.  The character is determined automatically depending on how many segments it is told to use. The b parameter tells it how much to temporarily rotate so that the letters are pointing in the right direction. The l parameter determines the linear distance between letters.

The t procedure steps to the next position and calls the r function a four times to create a triangle, rotating when appropriate.  I called it twice for the vertical side because that took fewer bytes than calling it once with special handling.  The end of the procedure positions the turtle for start of the next triangle, one step above.

Z is a special case, so we just print it directly and rotate as if we had just finished a triangle.  Finally, t is called 25 times.

Title: Alphabet triangle

Body:
You are to print this exact text:

```<code>A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
ABCDEFEDCBA
ABCDEFGFEDCBA
ABCDEFGHGFEDCBA
ABCDEFGHIHGFEDCBA
ABCDEFGHIJIHGFEDCBA
ABCDEFGHIJKJIHGFEDCBA
ABCDEFGHIJKLKJIHGFEDCBA
ABCDEFGHIJKLMLKJIHGFEDCBA
ABCDEFGHIJKLMNMLKJIHGFEDCBA
ABCDEFGHIJKLMNONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYZYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNONMLKJIHGFEDCBA
ABCDEFGHIJKLMNMLKJIHGFEDCBA
ABCDEFGHIJKLMLKJIHGFEDCBA
ABCDEFGHIJKLKJIHGFEDCBA
ABCDEFGHIJKJIHGFEDCBA
ABCDEFGHIJIHGFEDCBA
ABCDEFGHIHGFEDCBA
ABCDEFGHGFEDCBA
ABCDEFGFEDCBA
ABCDEFEDCBA
ABCDEDCBA
ABCDCBA
ABCBA
ABA
A
</code>```

Specs

Extra trailing newlines are allowed at the end of the output.

Extra trailing spaces (U+0020) are allowed at the end of each line, including the extra trailing newlines.

You can use all lowercase instead of all uppercase, but you cannot print partially lowercase partially uppercase.

You can return the text as a function output instead of printing it in a full program.

Scoring

Since this is a triangle, and a triangle has 3 sides, and 3 is a small number, your code should be small in terms of byte-count.

Body:
Logo, <s>232 207 196</s> 190 bytes

Did somebody say triangles?

Get out your compass and protractor, and let's do this the graphical way.  The geometry uses an equilateral triangle to align the results.  I previously had an isosceles triangle, but it involved too many decimal places.  This change also compacted the output, reducing the amount of screen prep and font changing I had to do.

I used the Calormen online interpreter to flesh this one out.  If you don't have enough screen real estate, it's going to wrap, but you can also fiddle with some numbers to take care of that.  I used the "F11" full-screen mode on my browser.

ht
pu
to r:n:b:l repeat:n[rt:b label char 90-:n lt:b fd:l] end
to t:s
fd 12 rt 120 bk 6
repeat 2[r:s 90 12]
repeat 2[rt 120 r:s 90-heading 24]
end
rt 90 label "Z lt 210
repeat 25[t repcount]

The r procedure draws a line of n characters.  The character is determined automatically depending on how many segments it is told to use. The b parameter tells it how much to temporarily rotate so that the letters are pointing in the right direction. The l parameter determines the linear distance between letters.

The t procedure steps to the next position and calls the r function a four times to create a triangle, rotating when appropriate.  I called it twice for the vertical side because that took fewer bytes than calling it once with special handling.  The end of the procedure positions the turtle for start of the next triangle, one step above.

Z is a special case, so we just print it directly and rotate as if we had just finished a triangle.  Finally, t is called 25 times.


问:
A newly discovered number: bleen!
"The Nobel Prize in mathematics was awarded to a California professor who has discovered a new number! The number is bleen, which he claims belongs between 6 and 7."  --George Carlin

In this challenge, you will print all Integers, inclusive, within the given input range.  Print numbers ascending or descending according to their input order.  That is, for input [n1, n2], print ascending if n1 < n2, descending if n1 > n2.

Since bleen is now an Integer number it may be used as input.  It must also be included in the output, between 6 and 7 where applicable.  Also note that -bleen exists between -7 and -6.

Input

Two Integers [n1, n2] in the range [-10, 10], inclusive, via your programming language's input of choice.

(Input may also contain bleen and -bleen!)

Output

Print all Integers starting at n1 and ending with n2, including the newly discovered bleen between 6 and 7.  Output can be a range of character separated numbers in some form your language supports - that is, comma or space separated.  One trailing space of output is okay.

Examples

```<code>Input:  1 10
Output: 1 2 3 4 5 6 bleen 7 8 9 10

Input:  -9 -4
Output: -9 -8 -7 -bleen -6 -5 -4

Input:  -8 bleen
Output: -8 -7 -bleen -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 bleen

Input:  9 1
Output: 9 8 7 bleen 6 5 4 3 2 1

Input:  2 -bleen
Output: 2 1 0 -1 -2 -3 -4 -5 -6 -bleen

Input:  -bleen 0
Output: -bleen -6 -5 -4 -3 -2 -1 0

Input:  bleen bleen
Output: bleen

Input:  2 2
Output: 2
</code>```

Additional notes

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

You may use any programming language, but standard loopholes are not allowed.

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

答:
Javascript (using external library) (343 bytes)

```<code>(a,b)=>{r="bleen";s="-"+r;c=d=>d==r?7:(d==s?-7:d);i=c(a);j=c(b);m=Math.min(i,j);n=Math.max(i,j);w=i<=j?_.RangeTo(i,j):_.RangeDown(i,Math.abs(j-i)+1);g=i<j?6:7;if(n>-7&&m<-6){w=w.InsertWhere("-bleen",x=>x==-7)}if(m<8&&n>6){w=w.InsertWhere("bleen",x=>x==g)}if(a==r||b==r){w=w.Where(x=>x!=7)}if(a==s||b==s){w=w.Where(x=>x!=-7)}return w.ToArray()}
</code>```

Link to lib: https://github.com/mvegh1/Enumerable

Screenshot:

ContentLicense: CC BY-SA 3.0

Title: A newly discovered number: bleen!

Body:
Javascript (using external library) (343 bytes)

(a,b)=>{r="bleen";s="-"+r;c=d=>d==r?7:(d==s?-7:d);i=c(a);j=c(b);m=Math.min(i,j);n=Math.max(i,j);w=i<=j?_.RangeTo(i,j):_.RangeDown(i,Math.abs(j-i)+1);g=i<j?6:7;if(n>-7&&m<-6){w=w.InsertWhere("-bleen",x=>x==-7)}if(m<8&&n>6){w=w.InsertWhere("bleen",x=>x==g)}if(a==r||b==r){w=w.Where(x=>x!=7)}if(a==s||b==s){w=w.Where(x=>x!=-7)}return w.ToArray()}

Link to lib: https://github.com/mvegh1/Enumerable

Screenshot:


问:
Simple redstone simulator
Redstone is a material in the game Minecraft, and it is used for many complex contraptions. For this program, you will only need to simulate three items: the redstone wire (noted with R), redstone torch (noted with T), and block (noted with B).

Here are a list of basic rules about how redstone works:

```<code>A redstone torch sends power to any adjacent redstone wire.
TRRRR
 ^This redstone wire is powered.

Redstone wire can only hold power for 15 blocks.
TRRRRRRRRRRRRRRRR
                ^This last wire is unpowered, because the torch is >15 blocks away.

A block is said to be powered if a powered redstone wire is found adjacent to it.
TRRRB
    ^This block is powered.

If a block next to a redstone torch is powered, then the torch stops emitting power.
T
R
R
R
B <This block is powered.
T <This redstone torch does not emit power because of the block next to it.
R <This redstone is unpowered because the torch is not providing power.
R
</code>```

Input will be given in two dimensional arrays up to a size of 64x64, like this:

```<code>TRRR
   B
TBRTRR
R
RRRRRRRRR
        R
   RRRRRR
</code>```

It is guaranteed that the input will not have any "clocks", or redstone powered by a torch pointing to the block that the torch is on. There will only be one redstone circuit in every input.

Your program must change each character to be a 1 or a 0, 1 indicating if this item is powered/emitting power, and a 0 if it is unpowered/not emitting power.

This input should have this output:

```<code>1111
   1
100000
1
111111111
        1
   001111
</code>```

This is a code-golf, so shortest code wins, as always.

答:
Haskell, 400

```<code>import Data.Char
import Data.List
f x=[(++[x]).tail,(x:).init]
h(' ':_)=' '
h('T':s)=if elem 'b's then 'T'else 't'
h('t':s)=h$'T':s
h('B':s)=if any(`elem`s)['e'..'s']then 'b'else 'B'
h('b':s)=h$'B':s
h(_:s)=max 'd'$chr$ord(maximum s)-1
o ' '=' '
o c|elem c"dTB"='0'
o _='1'
a=(map.map)o.(!!(64^2+16)).iterate(map(map h.transpose).transpose.(\l->[g l|g<-id:f(map(const ' ')$head l)++map map (f ' ')]))
</code>```

map(map h.transpose).transpose.(\l->[g l|g<-id:f(map(const ' ')$head l)++map map (f ' ')]) replaces each tile by a list of itself followed by its four neighbors, then maps that through h. h says for each tile how it reacts to neighbors: Torches turn off ('T' rather than 't') when there's a power block ('b') nearby, wires ('d' for dead through 's') imperfectly copy their most-powered neighbor (though cant get worse than dead), etc.

iterate repeats this step, (!!(64^2+16)) plucks out an iteration at which acyclic circuits are done converging, and I totally wrote it like that to give an intuitive bound, not to land at 400.

Title: Simple redstone simulator

Body:
Haskell, 400

import Data.Char
import Data.List
f x=[(++[x]).tail,(x:).init]
h(' ':_)=' '
h('T':s)=if elem 'b's then 'T'else 't'
h('t':s)=h$'T':s
h('B':s)=if any(`elem`s)['e'..'s']then 'b'else 'B'
h('b':s)=h$'B':s
h(_:s)=max 'd'$chr$ord(maximum s)-1
o ' '=' '
o c|elem c"dTB"='0'
o _='1'
a=(map.map)o.(!!(64^2+16)).iterate(map(map h.transpose).transpose.(\l->[g l|g<-id:f(map(const ' ')$head l)++map map (f ' ')]))

map(map h.transpose).transpose.(\l->[g l|g<-id:f(map(const ' ')$head l)++map map (f ' ')]) replaces each tile by a list of itself followed by its four neighbors, then maps that through h. h says for each tile how it reacts to neighbors: Torches turn off ('T' rather than 't') when there's a power block ('b') nearby, wires ('d' for dead through 's') imperfectly copy their most-powered neighbor (though cant get worse than dead), etc.

iterate repeats this step, (!!(64^2+16)) plucks out an iteration at which acyclic circuits are done converging, and I totally wrote it like that to give an intuitive bound, not to land at 400.


问:
Draw the national flag of France
There have been many other flag challenges posted but not one for the national flag of France. This week seems like an appropriate time.

Produce this flag in the fewest bytes possible:

The image must be in a ratio of 3:2, with size at least 78 pixels wide and 52 pixels tall.

Each stripe takes up one third of the width.

The stripe colors from left to right are RGB: (0, 85, 164), (255, 255, 255), (239, 65, 53).

The image can be saved to a file or piped raw to STDOUT in any common image file format, or it can be displayed.

Alternatively, output a block of text at least 78 characters wide made of non-whitespace characters that depicts the flag, using ANSI color codes to color it. (Use standard blue, white, and red.)

Built-in flag images/libraries are not allowed.

The shortest code in bytes wins.

Leaderboard

The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
ZX Spectrum Z80 assembly, <s>32</s>, 30 Bytes

```<code>    org 8000h

red:      equ 16
white:    equ 120
blue:     equ 8

start:
    ld    c,16     ;height
    ld    e,8      ; blue/offset/counter
    ld    hl,5800h
sheldon:
    ld    b,e      ;counter
fun:
    ld    (hl),e   ;blue
    inc   hl
    djnz  fun
    ld    b,e      ;counter
with:
    ld   (hl),white
    inc  hl
    djnz with
    ld   b,e       ;counter
flags:
    ld   (hl),red
    inc  hl
    djnz flags
    ld   d,b       ;e holds offset
    add  hl,de
    dec  c
    jr   nz,sheldon
    ret

    end

    30 bytes
</code>```

output is 24*8 pixels wide =192 pixels wide

and 16*8 pixels high =128 pixels high

edit 1: removed preload of de with two colours,shorter to directly load (hl):saves 1 byte

By not using "de" it can now transfer values instead of "a":saves 1 byte

ContentLicense: CC BY-SA 4.0

Title: Draw the national flag of France

Body:
ZX Spectrum Z80 assembly, <s>32</s>, 30 Bytes

    org 8000h

red:      equ 16
white:    equ 120
blue:     equ 8

start:
    ld    c,16     ;height
    ld    e,8      ; blue/offset/counter
    ld    hl,5800h
sheldon:
    ld    b,e      ;counter
fun:
    ld    (hl),e   ;blue
    inc   hl
    djnz  fun
    ld    b,e      ;counter
with:
    ld   (hl),white
    inc  hl
    djnz with
    ld   b,e       ;counter
flags:
    ld   (hl),red
    inc  hl
    djnz flags
    ld   d,b       ;e holds offset
    add  hl,de
    dec  c
    jr   nz,sheldon
    ret

    end

    30 bytes

output is 24*8 pixels wide =192 pixels wide

and 16*8 pixels high =128 pixels high

edit 1: removed preload of de with two colours,shorter to directly load (hl):saves 1 byte

By not using "de" it can now transfer values instead of "a":saves 1 byte


问:
Alphabet triangle
You are to print this exact text:

```<code>A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
ABCDEFEDCBA
ABCDEFGFEDCBA
ABCDEFGHGFEDCBA
ABCDEFGHIHGFEDCBA
ABCDEFGHIJIHGFEDCBA
ABCDEFGHIJKJIHGFEDCBA
ABCDEFGHIJKLKJIHGFEDCBA
ABCDEFGHIJKLMLKJIHGFEDCBA
ABCDEFGHIJKLMNMLKJIHGFEDCBA
ABCDEFGHIJKLMNONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYZYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNONMLKJIHGFEDCBA
ABCDEFGHIJKLMNMLKJIHGFEDCBA
ABCDEFGHIJKLMLKJIHGFEDCBA
ABCDEFGHIJKLKJIHGFEDCBA
ABCDEFGHIJKJIHGFEDCBA
ABCDEFGHIJIHGFEDCBA
ABCDEFGHIHGFEDCBA
ABCDEFGHGFEDCBA
ABCDEFGFEDCBA
ABCDEFEDCBA
ABCDEDCBA
ABCDCBA
ABCBA
ABA
A
</code>```

Specs

Extra trailing newlines are allowed at the end of the output.

Extra trailing spaces (U+0020) are allowed at the end of each line, including the extra trailing newlines.

You can use all lowercase instead of all uppercase, but you cannot print partially lowercase partially uppercase.

You can return the text as a function output instead of printing it in a full program.

Scoring

Since this is a triangle, and a triangle has 3 sides, and 3 is a small number, your code should be small in terms of byte-count.

答:
Convex, 21 bytes

```<code>U{[),U&)\¿@\N]}%)\¿@\
</code>```

Try it online!

Title: Alphabet triangle

Body:
Convex, 21 bytes

U{[),U&)\¿@\N]}%)\¿@\

Try it online!


答:
Python 3, 126 bytes

Input is in the form -5, 'bleen'

```<code>l=list(range(-10,11))
c='bleen'
s=l.insert
t=l.index
s(4,'-'+c)
s(18,c)
i,j=map(t,eval(input()))
d=1-2*(i<j)
print(l[i:j+d:d])
</code>```

Title: A newly discovered number: bleen!

Body:
"The Nobel Prize in mathematics was awarded to a California professor who has discovered a new number! The number is bleen, which he claims belongs between 6 and 7."  --George Carlin

In this challenge, you will print all Integers, inclusive, within the given input range.  Print numbers ascending or descending according to their input order.  That is, for input [n1, n2], print ascending if n1 < n2, descending if n1 > n2.

Since bleen is now an Integer number it may be used as input.  It must also be included in the output, between 6 and 7 where applicable.  Also note that -bleen exists between -7 and -6.

Input

Two Integers [n1, n2] in the range [-10, 10], inclusive, via your programming language's input of choice.

(Input may also contain bleen and -bleen!)

Output

Print all Integers starting at n1 and ending with n2, including the newly discovered bleen between 6 and 7.  Output can be a range of character separated numbers in some form your language supports - that is, comma or space separated.  One trailing space of output is okay.

Examples

```<code>Input:  1 10
Output: 1 2 3 4 5 6 bleen 7 8 9 10

Input:  -9 -4
Output: -9 -8 -7 -bleen -6 -5 -4

Input:  -8 bleen
Output: -8 -7 -bleen -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 bleen

Input:  9 1
Output: 9 8 7 bleen 6 5 4 3 2 1

Input:  2 -bleen
Output: 2 1 0 -1 -2 -3 -4 -5 -6 -bleen

Input:  -bleen 0
Output: -bleen -6 -5 -4 -3 -2 -1 0

Input:  bleen bleen
Output: bleen

Input:  2 2
Output: 2
</code>```

Additional notes

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

You may use any programming language, but standard loopholes are not allowed.

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

Body:
Python 3, 126 bytes

Input is in the form -5, 'bleen'

l=list(range(-10,11))
c='bleen'
s=l.insert
t=l.index
s(4,'-'+c)
s(18,c)
i,j=map(t,eval(input()))
d=1-2*(i<j)
print(l[i:j+d:d])


问:
Unsorted majorization of two lists

Definition

A vector a containing n elements is said to
majorize or
dominate a vector b with n
elements iff for all values k such that 1 ≤ k ≤ n, the sum of the first
element of a↓ through the kth element of a↓ is
greater than or equal to the sum of the first through kth elements of
b↓, where v↓ represents the vector v sorted in
descending order.

That is,

```<code>                          a_1 >= b_1
                    a_1 + a_2 >= b_1 + b_2
              a_1 + a_2 + a_3 >= b_1 + b_2 + b_3
                              ...
      a_1 + a_2 + ... + a_n-1 >= b_1 + b_2 + ... + b_n-1
a_1 + a_2 + ... + a_n-1 + a_n >= b_1 + b_2 + ... + b_n-1 + b_n
</code>```

where a and b are sorted in descending order.

For the purpose of this challenge, we will be using a slight generalization of
majorization: we will say a list is an unsorted majorization of another if
all of the above inequalities are true without sorting a and b. (This is,
of course, mathematically useless, but makes the challenge more interesting.)

Challenge

Given an input of two distinct lists a and b of integers in the range 0
through 255 (inclusive), both lists of length n ≥ 1, output whether the first
list unsorted-majorizes the second (a > b), the second unsorted-majorizes
the first (b > a), or neither.

You may optionally require the length of the two lists to be provided as input.
The output must always be one of three distinct values, but the values
themselves may be whatever you want (please specify which values represent a
> b, b > a, and neither in your answer).

Test cases for a > b:

```<code>[255] [254]
[3,2,1] [3,1,2]
[6,1,5,2,7] [2,5,4,3,7]
</code>```

Test cases for b > a:

```<code>[9,1] [10,0]
[6,5,4] [7,6,5]
[0,1,1,2,1,2] [0,1,2,1,2,1]
</code>```

Test cases for no majorization:

```<code>[200,100] [150,250]
[3,1,4] [2,3,3]
[9,9,9,9,9,0] [8,8,8,8,8,9]
</code>```

答:
ngn/apl, 11 bytes

```<code>{+/∪×+\⍺-⍵}
</code>```

Based on the method in @Leaky Nun's answer.

Given two lists A and B, find the difference between each value elementwise, or let C = A - B. Then, find the cumulative sums of C and take the sign of each. The sum of the unique sign values will be the result. If A > B, the result is 1, if A < B the result is -1, and if there is no majority the result is 0.

Try it online.

Title: Unsorted majorization of two lists

Body:
ngn/apl, 11 bytes

{+/∪×+\⍺-⍵}

Based on the method in @Leaky Nun's answer.

Given two lists A and B, find the difference between each value elementwise, or let C = A - B. Then, find the cumulative sums of C and take the sign of each. The sum of the unique sign values will be the result. If A > B, the result is 1, if A < B the result is -1, and if there is no majority the result is 0.

Try it online.


问:
Patch the Paragraph
In the spirit of Patch the Image, here's a similar challenge but with text.

Challenge

Bit rot has afflicted your precious text! Given a paragraph composed of ASCII characters, with a rectangular hole somewhere in it, your program should try to fill in the hole with appropriate text, so that the paragraph blends as best as possible.

Further definitions

The hole will always be rectangular, and it may span multiple lines.

There will only ever be one hole.

Note that the hole does not necessarily fall on word boundaries (in fact, it usually won't).

The hole will be at most 25% of the input paragraph, but may overlap or extend past the "end" of the "normal" text (see the Euclid or Badger examples below).

Since finding the hole is not the main point of this challenge, it will be composed solely of hash marks # to allow for easy identification.

No other location in the input paragraph will have a hash mark.

Your code cannot use the "normal" text in the examples below - it will only receive and process the text with the hole in it.

The input can be as a single multi-line string, as an array of strings (one element per line), as a file, etc. -- your choice of what is most convenient for your language.

If desired, an optional additional input detailing the coordinates of the hole can be taken (e.g., a tuple of coordinates or the like).

Please describe your algorithm in your submission.

Voting

Voters are asked to judge the entries based on how well the algorithm fills in the text hole. Some suggestions include the following:

Does the filled in area match the approximate distribution of spaces and punctuation as the rest of the paragraph?

Does the filled in area introduce faulty syntax? (e.g., two spaces in a row, a period followed by a question mark, an erroneous sequence like , ,, etc.)

If you squint your eyes (so you're not actually reading the text), can you see where the hole used to be?

If there aren't any CamelCase words outside the hole, does the hole contain any? If there aren't any Capitalized Letters outside the hole, does the hole contain any? If There Are A Lot Of Capitalized Letters Outside The Hole, does the hole contain a proportionate amount?

Validity Criterion

In order for a submission to be considered valid, it must not alter any text of the paragraph outside of the hole (including trailing spaces). A single trailing newline at the very end is optional.

Test Cases

Format is original paragraph in a code block, followed by the same paragraph with a hole. The paragraphs with the hole will be used for input.

1 (Patch the Image)

```<code>In a popular image editing software there is a feature, that patches (The term
used in image processing is inpainting as @minxomat pointed out.) a selected
area of an image, based on the information outside of that patch. And it does a
quite good job, considering it is just a program. As a human, you can sometimes
see that something is wrong, but if you squeeze your eyes or just take a short
glance, the patch seems to fill in the gap quite well.

In a popular image editing software there is a feature, that patches (The term
used in image processing is inpainting as @minxomat pointed out.) a selected
area of an image, #############information outside of that patch. And it does a
quite good job, co#############is just a program. As a human, you can sometimes
see that something#############t if you squeeze your eyes or just take a short
glance, the patch seems to fill in the gap quite well.
</code>```

2 (Gettysburg Address)

```<code>But, in a larger sense, we can not dedicate, we can not consecrate, we can not
hallow this ground. The brave men, living and dead, who struggled here, have
consecrated it, far above our poor power to add or detract. The world will
little note, nor long remember what we say here, but it can never forget what
they did here. It is for us the living, rather, to be dedicated here to the
unfinished work which they who fought here have thus far so nobly advanced. It
is rather for us to be here dedicated to the great task remaining before us-
that from these honored dead we take increased devotion to that cause for which
they gave the last full measure of devotion-that we here highly resolve that
these dead shall not have died in vain-that this nation, under God, shall have
a new birth of freedom-and that government of the people, by the people, for
the people, shall not perish from the earth.

But, in a larger sense, we can not dedicate, we can not consecrate, we can not
hallow this ground. The brave men, living and dead, who struggled here, have
consecrated it, far above our poor power to add or detract. The world will
little note, nor long remember what we say here, but it can never forget what
they did here. It is for us the living, rather, to be dedicated here to the
unfinished work which they who fought here h######################advanced. It
is rather for us to be here dedicated to the######################before us-
that from these honored dead we take increas######################use for which
they gave the last full measure of devotion-######################solve that
these dead shall not have died in vain-that ######################, shall have
a new birth of freedom-and that government of the people, by the people, for
the people, shall not perish from the earth.
</code>```

3 (Lorem Ipsum)

```<code>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo conse################irure dolor in reprehenderit
in voluptate velit esse cil################giat nulla pariatur. Excepteur
sint occaecat cupidatat non################in culpa qui officia deserunt
mollit anim id est laborum.
</code>```

4 (Jabberwocky)

```<code>'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.

'Twas brillig, and the slithy toves
Did gyre a######### in the wabe;
All mimsy #########borogoves,
And the mome raths outgrabe.
</code>```

5 (Euclid's proof of the Pythagorean Theorem)

```<code>1.Let ACB be a right-angled triangle with right angle CAB.
2.On each of the sides BC, AB, and CA, squares are drawn,
CBDE, BAGF, and ACIH, in that order. The construction of
squares requires the immediately preceding theorems in Euclid,
and depends upon the parallel postulate. [footnote 14]
3.From A, draw a line parallel to BD and CE. It will
perpendicularly intersect BC and DE at K and L, respectively.
4.Join CF and AD, to form the triangles BCF and BDA.
5.Angles CAB and BAG are both right angles; therefore C, A,
and G are collinear. Similarly for B, A, and H.
6.Angles CBD and FBA are both right angles; therefore angle ABD
equals angle FBC, since both are the sum of a right angle and angle ABC.
7.Since AB is equal to FB and BD is equal to BC, triangle ABD
must be congruent to triangle FBC.
8.Since A-K-L is a straight line, parallel to BD, then rectangle
BDLK has twice the area of triangle ABD because they share the base
BD and have the same altitude BK, i.e., a line normal to their common
base, connecting the parallel lines BD and AL. (lemma 2)
9.Since C is collinear with A and G, square BAGF must be twice in area
to triangle FBC.
10.Therefore, rectangle BDLK must have the same area as square BAGF = AB^2.
11.Similarly, it can be shown that rectangle CKLE must have the same
area as square ACIH = AC^2.
12.Adding these two results, AB^2 + AC^2 = BD × BK + KL × KC
13.Since BD = KL, BD × BK + KL × KC = BD(BK + KC) = BD × BC
14.Therefore, AB^2 + AC^2 = BC^2, since CBDE is a square.

1.Let ACB be a right-angled triangle with right angle CAB.
2.On each of the sides BC, AB, and CA, squares are drawn,
CBDE, BAGF, and ACIH, in that order. The construction of
squares requires the immediately preceding theorems in Euclid,
and depends upon the parallel postulate. [footnote 14]
3.From A, draw a line parallel to BD and CE. It will
perpendicularly intersect BC and DE at K and L, respectively.
4.Join CF and AD, to form the triangles BCF and BDA.
5.Angles CAB and BAG are both right angles; therefore C, A,
and G are #############milarly for B, A, and H.
6.Angles C#############e both right angles; therefore angle ABD
equals ang############# both are the sum of a right angle and angle ABC.
7.Since AB#############FB and BD is equal to BC, triangle ABD
must be co#############iangle FBC.
8.Since A-#############ight line, parallel to BD, then rectangle
BDLK has t############# of triangle ABD because they share the base
BD and hav#############titude BK, i.e., a line normal to their common
base, conn#############rallel lines BD and AL. (lemma 2)
9.Since C #############with A and G, square BAGF must be twice in area
to triangl#############
10.Therefo############# BDLK must have the same area as square BAGF = AB^2.
11.Similar############# shown that rectangle CKLE must have the same
area as square ACIH = AC^2.
12.Adding these two results, AB^2 + AC^2 = BD × BK + KL × KC
13.Since BD = KL, BD × BK + KL × KC = BD(BK + KC) = BD × BC
14.Therefore, AB^2 + AC^2 = BC^2, since CBDE is a square.
</code>```

6 (Badger, Badger, Badger by weebl)

```<code>Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, mushroom, a-
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, mushroom, a-
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mush-mushroom, a
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Argh! Snake, a snake!
Snaaake! A snaaaake, oooh its a snake!

Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, mushroom, a-
Badger##################badger, badger,
badger##################badger, badger
Mushro##################
Badger##################badger, badger,
badger##################badger, badger
Mush-mushroom, a
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Argh! Snake, a snake!
Snaaake! A snaaaake, oooh its a snake!
</code>```

答:
Java Shakespeare

Who needs a grasp of standard english conventions? Just make your own! Just like the bard was allowed to make up his own words. This bot doesn't worry to much about correcting the cut off words, he really just inserts random words. The result is some beautiful Poetry. As a bonus feature the bard is of a higher caliber and can handle multiple holes provided they are the same size!

Sample Input

```
 From fairest creatures we desire increase,
  That thereby beauty's rose might never die,
  But as the riper should by time decease,
  His tender############bear his memory:
  But thou c############ thine own bright eyes,
  Feed'st th############ame with self-substantial fuel,
  Making a famine where abundance lies,
  Thy self thy foe, to thy sweet self too cruel:
  Thou that art now the world's fresh ornament,
  And only herald to the gaudy spring,
  Within thine own bud buriest thy content,
  And tender churl mak'st was############ding:
    Pity the world, or else t############be,
    To eat the world's due, b############and thee.

                     2
  When forty winters shall besiege thy brow,
  And dig deep trenches in thy beauty's field,
  Thy youth's proud livery so gazed on now,
  Will be a tattered weed of small worth held:
  Then being asked, where all thy beauty lies,
  Where all the treasure of thy lusty days;
  To say within thine own deep sunken eyes,
  Were an all-eating shame, and thriftless praise.
  How much more praise deserved thy beauty's use,
  If thou couldst answer 'This fair child of mine
  Shall sum my count, and make my old excuse'
  Proving his beauty by succession thine.
    This were to be new made when thou art old,
    And see thy blood warm when thou feel'st it cold.

                     3
  Look in thy glass and tell the face thou viewest,
  Now is the time that face should form another,
  Whose fresh repair if now thou not renewest,
  Thou dost beguile the world, unbless some mother.
  For where is she so fair whose uneared womb
  Disdains the tillage of thy husbandry?
  Or who is he so fond will be the tomb,
  Of his self-love to stop posterity?
  Thou art thy mother's glass and she in thee
  Calls back the lovely April of her prime,
  So thou through windows of thine age shalt see,
  Despite of ############s thy golden time.
    But if th############mbered not to be,
    Die singl############image dies with thee.

```

Beautiful output

```
 From fairest creatures we desire increase,
  That thereby beauty's rose might never die,
  But as the riper should by time decease,
  His tender should of bear his memory:
  But thou c all mbered  thine own bright eyes,
  Feed'st th Proving Or ame with self-substantial fuel,
  Making a famine where abundance lies,
  Thy self thy foe, to thy sweet self too cruel:
  Thou that art now the world's fresh ornament,
  And only herald to the gaudy spring,
  Within thine own bud buriest thy content,
  And tender churl mak'st was he Thou my ding:
    Pity the world, or else t So the the be,
    To eat the world's due, b t thine so and thee.

                     2
  When forty winters shall besiege thy brow,
  And dig deep trenches in thy beauty's field,
  Thy youth's proud livery so gazed on now,
  Will be a tattered weed of small worth held:
  Then being asked, where all thy beauty lies,
  Where all the treasure of thy lusty days;
  To say within thine own deep sunken eyes,
  Were an all-eating shame, and thriftless praise.
  How much more praise deserved thy beauty's use,
  If thou couldst answer 'This fair child of mine
  Shall sum my count, and make my old excuse'
  Proving his beauty by succession thine.
    This were to be new made when thou art old,
    And see thy blood warm when thou feel'st it cold.

                     3
  Look in thy glass and tell the face thou viewest,
  Now is the time that face should form another,
  Whose fresh repair if now thou not renewest,
  Thou dost beguile the world, unbless some mother.
  For where is she so fair whose uneared womb
  Disdains the tillage of thy husbandry?
  Or who is he so fond will be the tomb,
  Of his self-love to stop posterity?
  Thou art thy mother's glass and she in thee
  Calls back the lovely April of her prime,
  So thou through windows of thine age shalt see,
  Despite of  Look gazed s thy golden time.
    But if th When be, mbered not to be,
    Die singl repair the image dies with thee.
```

The last couple lines are deeply poetic if I do say so myself.
It performs suprisingly well on the gettysburg address as well.

```<code>But, in a larger sense, we can not dedicate, we can not consecrate, we can not
hallow this ground. The brave men, living and dead, who struggled here, have
consecrated it, far above our poor power to add or detract. The world will
little note, nor long remember what we say here, but it can never forget what
they did here. It is for us the living, rather, to be dedicated here to the
unfinished work which they who fought here h to of rather us of advanced. It
is rather for us to be here dedicated to the who be it, vain who before us
that from these honored dead we take increas be dead the the what use for which
they gave the last full measure of devotion  dead government The solve that
these dead shall not have died in vain that  the take nor world , shall have
a new birth of freedom and that government of the people, by the people, for
the people, shall not perish from the earth.
</code>```

Lets see what makes Shakespeare tick. Here is the code. Essentially he strives to build a vocabulary base from the input. He then uses these words and randomly places them in the hole (ensuring that it fits nicely). He is deterministic as he uses a fixed seed for randomness.

```<code>package stuff;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;

/**
 *
 * @author rohan
 */
public class PatchTheParagraph {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("File Name :");
        String[] text = getWordsFromFile(in.nextLine());
System.out.println("==ORIGINAL==");
        for(String s:text){
    System.out.println(s);
}
                    int lengthOfHole= 0;
        int rows = 0;
            for(String s: text){
                s = s.replaceAll("[^#]", "");

//      System.out.println(s);
                if(s.length()>0){
                    lengthOfHole = s.length();
                rows++;
                }
            }
            ArrayList<String> words = new ArrayList<>();
            words.add("I");
            for(String s:text){
                String[] w = s.replaceAll("#", " ").split(" ");
for(String a :w){
    words.add(a);
            }

            }
                        Iterator<String> j = words.iterator();
            while(j.hasNext()){
                String o;
                if((o = j.next()).equals("")){
                    j.remove();
                }
            }
            System.out.println(words);
            Stack<String> out = new Stack<>();
            String hashRow = "";
            for(int i = 0;i<lengthOfHole;i++){
                hashRow+="#";
            }

        for(int i = 0;i<rows;i++){
            int length = lengthOfHole-1;
            String outPut = " ";
            while(length>2){
String wordAttempt = words.get(getRandom(words.size()-1));
while(wordAttempt.length()>length-1){
 wordAttempt = words.get(getRandom(words.size()-1));
}
length -= wordAttempt.length()+1;
            outPut+=wordAttempt;
                outPut+=" ";
            }
        out.push(outPut);
    }
System.out.println("==PATCHED==");
        for(String s : text){
            if(s.contains(hashRow)){
                System.out.println(s.replaceAll(hashRow,out.pop()));
            }else{
                System.out.println(s);
            }
        }
                                    }
public static final Random r = new Random(42);
    public static int getRandom(int max){
    return (int) (max*r.nextDouble());
}
    /**
     *
     * @param fileName is the path to the file or just the name if it is local
     * @return the number of lines in fileName
     */
    public static int getLengthOfFile(String fileName) {
        int length = 0;
        try {
            File textFile = new File(fileName);
            Scanner sc = new Scanner(textFile);
            while (sc.hasNextLine()) {
                sc.nextLine();
                length++;
            }
        } catch (Exception e) {
System.err.println(e);
        }
        return length;
    }

    /**
     *
     * @param fileName is the path to the file or just the name if it is local
     * @return an array of Strings where each string is one line from the file
     * fileName.
     */
    public static String[] getWordsFromFile(String fileName) {
        int lengthOfFile = getLengthOfFile(fileName);
        String[] wordBank = new String[lengthOfFile];
        int i = 0;
        try {
            File textFile = new File(fileName);
            Scanner sc = new Scanner(textFile);
            for (i = 0; i < lengthOfFile; i++) {
                wordBank[i] = sc.nextLine();
            }
            return wordBank;
        } catch (Exception e) {
            System.err.println(e);
            System.exit(55);
        }
        return null;
    }
}
</code>```

Most of Shakespeare's poetry is public domain.

Title: Patch the Paragraph

Body:
Java Shakespeare

Who needs a grasp of standard english conventions? Just make your own! Just like the bard was allowed to make up his own words. This bot doesn't worry to much about correcting the cut off words, he really just inserts random words. The result is some beautiful Poetry. As a bonus feature the bard is of a higher caliber and can handle multiple holes provided they are the same size!

Sample Input

 From fairest creatures we desire increase,
  That thereby beauty's rose might never die,
  But as the riper should by time decease,
  His tender############bear his memory:
  But thou c############ thine own bright eyes,
  Feed'st th############ame with self-substantial fuel,
  Making a famine where abundance lies,
  Thy self thy foe, to thy sweet self too cruel:
  Thou that art now the world's fresh ornament,
  And only herald to the gaudy spring,
  Within thine own bud buriest thy content,
  And tender churl mak'st was############ding:
    Pity the world, or else t############be,
    To eat the world's due, b############and thee.

                     2
  When forty winters shall besiege thy brow,
  And dig deep trenches in thy beauty's field,
  Thy youth's proud livery so gazed on now,
  Will be a tattered weed of small worth held:
  Then being asked, where all thy beauty lies,
  Where all the treasure of thy lusty days;
  To say within thine own deep sunken eyes,
  Were an all-eating shame, and thriftless praise.
  How much more praise deserved thy beauty's use,
  If thou couldst answer 'This fair child of mine
  Shall sum my count, and make my old excuse'
  Proving his beauty by succession thine.
    This were to be new made when thou art old,
    And see thy blood warm when thou feel'st it cold.

                     3
  Look in thy glass and tell the face thou viewest,
  Now is the time that face should form another,
  Whose fresh repair if now thou not renewest,
  Thou dost beguile the world, unbless some mother.
  For where is she so fair whose uneared womb
  Disdains the tillage of thy husbandry?
  Or who is he so fond will be the tomb,
  Of his self-love to stop posterity?
  Thou art thy mother's glass and she in thee
  Calls back the lovely April of her prime,
  So thou through windows of thine age shalt see,
  Despite of ############s thy golden time.
    But if th############mbered not to be,
    Die singl############image dies with thee.

Beautiful output

 From fairest creatures we desire increase,
  That thereby beauty's rose might never die,
  But as the riper should by time decease,
  His tender should of bear his memory:
  But thou c all mbered  thine own bright eyes,
  Feed'st th Proving Or ame with self-substantial fuel,
  Making a famine where abundance lies,
  Thy self thy foe, to thy sweet self too cruel:
  Thou that art now the world's fresh ornament,
  And only herald to the gaudy spring,
  Within thine own bud buriest thy content,
  And tender churl mak'st was he Thou my ding:
    Pity the world, or else t So the the be,
    To eat the world's due, b t thine so and thee.

                     2
  When forty winters shall besiege thy brow,
  And dig deep trenches in thy beauty's field,
  Thy youth's proud livery so gazed on now,
  Will be a tattered weed of small worth held:
  Then being asked, where all thy beauty lies,
  Where all the treasure of thy lusty days;
  To say within thine own deep sunken eyes,
  Were an all-eating shame, and thriftless praise.
  How much more praise deserved thy beauty's use,
  If thou couldst answer 'This fair child of mine
  Shall sum my count, and make my old excuse'
  Proving his beauty by succession thine.
    This were to be new made when thou art old,
    And see thy blood warm when thou feel'st it cold.

                     3
  Look in thy glass and tell the face thou viewest,
  Now is the time that face should form another,
  Whose fresh repair if now thou not renewest,
  Thou dost beguile the world, unbless some mother.
  For where is she so fair whose uneared womb
  Disdains the tillage of thy husbandry?
  Or who is he so fond will be the tomb,
  Of his self-love to stop posterity?
  Thou art thy mother's glass and she in thee
  Calls back the lovely April of her prime,
  So thou through windows of thine age shalt see,
  Despite of  Look gazed s thy golden time.
    But if th When be, mbered not to be,
    Die singl repair the image dies with thee.

The last couple lines are deeply poetic if I do say so myself.
It performs suprisingly well on the gettysburg address as well.

But, in a larger sense, we can not dedicate, we can not consecrate, we can not
hallow this ground. The brave men, living and dead, who struggled here, have
consecrated it, far above our poor power to add or detract. The world will
little note, nor long remember what we say here, but it can never forget what
they did here. It is for us the living, rather, to be dedicated here to the
unfinished work which they who fought here h to of rather us of advanced. It
is rather for us to be here dedicated to the who be it, vain who before us
that from these honored dead we take increas be dead the the what use for which
they gave the last full measure of devotion  dead government The solve that
these dead shall not have died in vain that  the take nor world , shall have
a new birth of freedom and that government of the people, by the people, for
the people, shall not perish from the earth.

Lets see what makes Shakespeare tick. Here is the code. Essentially he strives to build a vocabulary base from the input. He then uses these words and randomly places them in the hole (ensuring that it fits nicely). He is deterministic as he uses a fixed seed for randomness.

package stuff;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;

/**
 *
 * @author rohan
 */
public class PatchTheParagraph {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("File Name :");
        String[] text = getWordsFromFile(in.nextLine());
System.out.println("==ORIGINAL==");
        for(String s:text){
    System.out.println(s);
}
                    int lengthOfHole= 0;
        int rows = 0;
            for(String s: text){
                s = s.replaceAll("[^#]", "");

//      System.out.println(s);
                if(s.length()>0){
                    lengthOfHole = s.length();
                rows++;
                }
            }
            ArrayList<String> words = new ArrayList<>();
            words.add("I");
            for(String s:text){
                String[] w = s.replaceAll("#", " ").split(" ");
for(String a :w){
    words.add(a);
            }

            }
                        Iterator<String> j = words.iterator();
            while(j.hasNext()){
                String o;
                if((o = j.next()).equals("")){
                    j.remove();
                }
            }
            System.out.println(words);
            Stack<String> out = new Stack<>();
            String hashRow = "";
            for(int i = 0;i<lengthOfHole;i++){
                hashRow+="#";
            }

        for(int i = 0;i<rows;i++){
            int length = lengthOfHole-1;
            String outPut = " ";
            while(length>2){
String wordAttempt = words.get(getRandom(words.size()-1));
while(wordAttempt.length()>length-1){
 wordAttempt = words.get(getRandom(words.size()-1));
}
length -= wordAttempt.length()+1;
            outPut+=wordAttempt;
                outPut+=" ";
            }
        out.push(outPut);
    }
System.out.println("==PATCHED==");
        for(String s : text){
            if(s.contains(hashRow)){
                System.out.println(s.replaceAll(hashRow,out.pop()));
            }else{
                System.out.println(s);
            }
        }
                                    }
public static final Random r = new Random(42);
    public static int getRandom(int max){
    return (int) (max*r.nextDouble());
}
    /**
     *
     * @param fileName is the path to the file or just the name if it is local
     * @return the number of lines in fileName
     */
    public static int getLengthOfFile(String fileName) {
        int length = 0;
        try {
            File textFile = new File(fileName);
            Scanner sc = new Scanner(textFile);
            while (sc.hasNextLine()) {
                sc.nextLine();
                length++;
            }
        } catch (Exception e) {
System.err.println(e);
        }
        return length;
    }

    /**
     *
     * @param fileName is the path to the file or just the name if it is local
     * @return an array of Strings where each string is one line from the file
     * fileName.
     */
    public static String[] getWordsFromFile(String fileName) {
        int lengthOfFile = getLengthOfFile(fileName);
        String[] wordBank = new String[lengthOfFile];
        int i = 0;
        try {
            File textFile = new File(fileName);
            Scanner sc = new Scanner(textFile);
            for (i = 0; i < lengthOfFile; i++) {
                wordBank[i] = sc.nextLine();
            }
            return wordBank;
        } catch (Exception e) {
            System.err.println(e);
            System.exit(55);
        }
        return null;
    }
}

Most of Shakespeare's poetry is public domain.


答:
Python 3.5, 85 bytes:

```<code>lambda*e:[all(sum(g[:k])>=sum(h[:k])for k in range(1,-~len(h)))for g,h in[e,e[::-1]]]
</code>```

An anonymous lambda function. Returns [True,False] if a>b, [False,True] if b>a, or [False,False] if neither of those are true. I hope this is okay.

Try It Online! (Ideone)

Title: Unsorted majorization of two lists

Body:
Definition

A vector a containing n elements is said to
majorize or
dominate a vector b with n
elements iff for all values k such that 1 ≤ k ≤ n, the sum of the first
element of a↓ through the kth element of a↓ is
greater than or equal to the sum of the first through kth elements of
b↓, where v↓ represents the vector v sorted in
descending order.

That is,

```<code>                          a_1 >= b_1
                    a_1 + a_2 >= b_1 + b_2
              a_1 + a_2 + a_3 >= b_1 + b_2 + b_3
                              ...
      a_1 + a_2 + ... + a_n-1 >= b_1 + b_2 + ... + b_n-1
a_1 + a_2 + ... + a_n-1 + a_n >= b_1 + b_2 + ... + b_n-1 + b_n
</code>```

where a and b are sorted in descending order.

For the purpose of this challenge, we will be using a slight generalization of
majorization: we will say a list is an unsorted majorization of another if
all of the above inequalities are true without sorting a and b. (This is,
of course, mathematically useless, but makes the challenge more interesting.)

Challenge

Given an input of two distinct lists a and b of integers in the range 0
through 255 (inclusive), both lists of length n ≥ 1, output whether the first
list unsorted-majorizes the second (a > b), the second unsorted-majorizes
the first (b > a), or neither.

You may optionally require the length of the two lists to be provided as input.
The output must always be one of three distinct values, but the values
themselves may be whatever you want (please specify which values represent a
> b, b > a, and neither in your answer).

Test cases for a > b:

```<code>[255] [254]
[3,2,1] [3,1,2]
[6,1,5,2,7] [2,5,4,3,7]
</code>```

Test cases for b > a:

```<code>[9,1] [10,0]
[6,5,4] [7,6,5]
[0,1,1,2,1,2] [0,1,2,1,2,1]
</code>```

Test cases for no majorization:

```<code>[200,100] [150,250]
[3,1,4] [2,3,3]
[9,9,9,9,9,0] [8,8,8,8,8,9]
</code>```

Body:
Python 3.5, 85 bytes:

lambda*e:[all(sum(g[:k])>=sum(h[:k])for k in range(1,-~len(h)))for g,h in[e,e[::-1]]]

An anonymous lambda function. Returns [True,False] if a>b, [False,True] if b>a, or [False,False] if neither of those are true. I hope this is okay.

Try It Online! (Ideone)


问:
The real knapsack problem
Given

the number of goods N

positive weight of each good weight[N]

positive profit of each good profit[N]

and a positive number W which is the knapsack capacity.

This problem is called “the zero-one knapsack” for choosing the most beneficial goods for the knapsack of limited capacity.

Example:

The number of goods (items)   :   5

Weight of each item (kg)  :   {2, 3, 5, 7, 8} which apply to item 1, item 2, ...... item 5 in that order

Value of each item (10,000 yen)   :   {2, 4, 8, 9, 10} which apply to item 1, item 2, .... item 5 in that order

Capacity of the knapsack  :   10 kg

Among the five goods:

```<code>Goods chosen            Total weight    Total value
Goods 1, 2 and 3    2 + 3 + 5 = 10  2 + 4 + 8 = 14   <- Maximum
</code>```

答:
Python, 236 Charaters

Okay, I guess I'll bite.

```<code>from itertools import *
def k(w,p,c):
    n=len(w)
    r=range(n)
    return max(filter(lambda y:y[1]<=c,[(s,sum(map(lambda y:w[y],s)),sum(map(lambda y:p[y],s))) for s in chain.from_iterable(combinations(r,u) for u in r+[n])]),key=lambda y:y[2])[0]
</code>```

Usage

The k function takes three arguments: a list containing the weights, a list containing the profits, and the capacity of the knapsack.  Here is how to call it given the example above:

```<code>> print k([2,3,5,7,8], [2,4,8,9,10], 10)
(0, 1, 2)
</code>```

Meaning that items 0, 1, and 2 are the optimal solution.

Title: The real knapsack problem

Body:
Python, 236 Charaters

Okay, I guess I'll bite.

from itertools import *
def k(w,p,c):
    n=len(w)
    r=range(n)
    return max(filter(lambda y:y[1]<=c,[(s,sum(map(lambda y:w[y],s)),sum(map(lambda y:p[y],s))) for s in chain.from_iterable(combinations(r,u) for u in r+[n])]),key=lambda y:y[2])[0]

Usage

The k function takes three arguments: a list containing the weights, a list containing the profits, and the capacity of the knapsack.  Here is how to call it given the example above:

> print k([2,3,5,7,8], [2,4,8,9,10], 10)
(0, 1, 2)

Meaning that items 0, 1, and 2 are the optimal solution.


答:
Pyth, 13 bytes

```<code>L+bt_bjyyM._G
</code>```

Demonstration

L+bt_b Concatenates a thing with its reverse without the first element. Define as y.

._G: Form all prefixes of the alphabet

yM: Apply y to each element.

y: Apply y to the list as a whole.

j: Join on newlines.

Title: Alphabet triangle

Body:
Pyth, 13 bytes

L+bt_bjyyM._G

Demonstration

L+bt_b Concatenates a thing with its reverse without the first element. Define as y.

._G: Form all prefixes of the alphabet

yM: Apply y to each element.

y: Apply y to the list as a whole.

j: Join on newlines.


问:
Turtles All the Way Down
Write a program or function that takes in a positive integer and prints or returns a stack of that many ASCII-art turtles, where each turtle is larger than the one above it.

Specifically, if the input is 1, the output should be:

```<code> __
/,,\o
</code>```

If the input is 2:

```<code>  __
o/,,\
 ____
/,__,\o
</code>```

If the input is 3:

```<code>   __
  /,,\o
  ____
o/,__,\
 ______
/,____,\o
</code>```

If the input is 4:

```<code>    __
  o/,,\
   ____
  /,__,\o
  ______
o/,____,\
 ________
/,______,\o
</code>```

If the input is 5:

```<code>     __
    /,,\o
    ____
  o/,__,\
   ______
  /,____,\o
  ________
o/,______,\
 __________
/,________,\o
</code>```

And so on in the same pattern for larger inputs.

Note that:

The head (the o) of the bottom turtle is always on the right. The heads of the turtles above then alternate back and forth.

No lines may have trailing spaces.

Superfluous leading spaces are not allowed. (i.e. the back of the bottom turtle should be at the start of the line.)

A single optional trailing newline is allowed.

The shortest code in bytes wins.

Title: Turtles All the Way Down

Body:
Ruby, 100 bytes

Recursive solution. Try it online!

f=->n,i=1{f[n-1,i+1]if n>1;puts' '*i+?_*n*2,"%#{i-1}s/,#{?_*2*~-n},\\"%(i<2?'':'o '[i%2])+' o'[i%2]}


Title: Alphabet triangle

Body:
Julia 0.4, 84 bytes

!()=(- =join;a=-char(65:90);b=[a[1:x+1]*a[x:~0:1]for x=0:25];vcat(b,b[25:~0:1])-"
")

Try it online!


答:
Batch, 256 bytes

```<code>@set i=echo
@%i%off
set u=
for /l %%j in (2,2,%1)do call set i=%%i%%
set/af=%1^&1
if %f%==1 %i% __&%i%/,,\o&set u=__
for /l %%j in (2,2,%1)do call:l
exit/b
:l
set i=%i:~0,-2%
%i%  _%u%_
%i%o/,%u%,\
%i% __%u%__
%i%/,_%u%_,\o
set u=__%u%__
</code>```

Note that line 1 has a trailing space and line 4 has two trailing spaces. i therefore contains an echo command with the appropriate amount of indentation for each turtle. Meanwhile u contains the number of underscores in alternate turtles. A leading odd turtle is special-cased and then the rest of the turtles are output in pairs.

Title: Turtles All the Way Down

Body:
Write a program or function that takes in a positive integer and prints or returns a stack of that many ASCII-art turtles, where each turtle is larger than the one above it.

Specifically, if the input is 1, the output should be:

```<code> __
/,,\o
</code>```

If the input is 2:

```<code>  __
o/,,\
 ____
/,__,\o
</code>```

If the input is 3:

```<code>   __
  /,,\o
  ____
o/,__,\
 ______
/,____,\o
</code>```

If the input is 4:

```<code>    __
  o/,,\
   ____
  /,__,\o
  ______
o/,____,\
 ________
/,______,\o
</code>```

If the input is 5:

```<code>     __
    /,,\o
    ____
  o/,__,\
   ______
  /,____,\o
  ________
o/,______,\
 __________
/,________,\o
</code>```

And so on in the same pattern for larger inputs.

Note that:

The head (the o) of the bottom turtle is always on the right. The heads of the turtles above then alternate back and forth.

No lines may have trailing spaces.

Superfluous leading spaces are not allowed. (i.e. the back of the bottom turtle should be at the start of the line.)

A single optional trailing newline is allowed.

The shortest code in bytes wins.

Body:
Batch, 256 bytes

@set i=echo
@%i%off
set u=
for /l %%j in (2,2,%1)do call set i=%%i%%
set/af=%1^&1
if %f%==1 %i% __&%i%/,,\o&set u=__
for /l %%j in (2,2,%1)do call:l
exit/b
:l
set i=%i:~0,-2%
%i%  _%u%_
%i%o/,%u%,\
%i% __%u%__
%i%/,_%u%_,\o
set u=__%u%__

Note that line 1 has a trailing space and line 4 has two trailing spaces. i therefore contains an echo command with the appropriate amount of indentation for each turtle. Meanwhile u contains the number of underscores in alternate turtles. A leading odd turtle is special-cased and then the rest of the turtles are output in pairs.


问:
Smallest sum (and largest difference) of two 3-digit integers
Given six unique non-negative integers, print the two 3-digit integers comprised of those numbers that sum to the smallest amount.

Additionally,

If there is more than one set of numbers that meets the smallest-sum requirement, print the two that have the greatest difference. For example, 269 + 157 = 267 + 159 = 426; however, 269 - 157 > 267 - 159, so the first set should be printed.

Print the numbers on the same line largest -> smallest, separated by a single space.

Zero (0) cannot be used as a leading number.

Inputs will always be digits.

Testcases

```<code>input        | output
2 6 5 1 9 7  | 269 157
1 9 5 0 8 3  | 359 108
1 2 3 4 5 6  | 246 135
</code>```

Scoring

As this is code golf, shortest entry wins.

答:
Jelly, 12 bytes

```<code>Ṣs3¬Þ€Fs2ZḌṚ
</code>```

Try it online! or verify all test cases.

Background

Consider six digits a < b < c < d < e < f.

If a ≠ 0, a number pair of three-digit integers with minimal sum must clearly use a and b for the leftmost digits, c and d for the middle digits, and e and f for the rightmost digits.

That gives eight possible arrangements with identical sums (100(a + b) + 10(c + d) + (e + f)).

Since the difference should be as large as possible, all digits of the first integer should be larger than the corresponding digits of the second integer, leaving bdf10, ace10 as the optimal arrangement (difference 100(b - a) + 10(d - c)+ (f - e)).

Finally, if a = 0, a should still occur as early as possible (as middle digit), and a similar process reveals that the pair cdf10, bae10 is the correct solution.

How it works

```<code>Ṣs3¬Þ€Fs2ZḌṚ  Main link. Argument: <a, b, c, d, e, f> (in any order)

Ṣ             Sort; yield [a, b, c, d, e, f].
 s3           Split into triplets; yield [[a, b, c], [d, e, f]].
   ¬Þ€        Sort each triplet by logical NOT.
              If a ≠ 0, all digits have logical NOT 0, so this leaves the triplets
              unaltered. If a = 0, its logical NOT is 1, so the first triplet is
              sorted as [b, c, a], leaving [[b, c, a], [d, e, f]].
      F       Flatten; yield [a, b, c, d, e, f] or [b, c, a, d, e, f].
       s2     Split into pairs; yield [[a, b], [c, d], [e, f]] or
              [[b, c], [a, d], [e, f]].
         Z    Zip; yield [[a, c, e], [b, d, f]] or [[b, a, e], [c, d, f]].
          Ḍ   Undecimal; convert each triplet from base 10 to integer.
           Ṛ  Reverse the order of the generated integers.
</code>```

Body:
Jelly, 12 bytes

Ṣs3¬Þ€Fs2ZḌṚ

Try it online! or verify all test cases.

Background

Consider six digits a < b < c < d < e < f.

If a ≠ 0, a number pair of three-digit integers with minimal sum must clearly use a and b for the leftmost digits, c and d for the middle digits, and e and f for the rightmost digits.

That gives eight possible arrangements with identical sums (100(a + b) + 10(c + d) + (e + f)).

Since the difference should be as large as possible, all digits of the first integer should be larger than the corresponding digits of the second integer, leaving bdf10, ace10 as the optimal arrangement (difference 100(b - a) + 10(d - c)+ (f - e)).

Finally, if a = 0, a should still occur as early as possible (as middle digit), and a similar process reveals that the pair cdf10, bae10 is the correct solution.

How it works

Ṣs3¬Þ€Fs2ZḌṚ  Main link. Argument: <a, b, c, d, e, f> (in any order)

Ṣ             Sort; yield [a, b, c, d, e, f].
 s3           Split into triplets; yield [[a, b, c], [d, e, f]].
   ¬Þ€        Sort each triplet by logical NOT.
              If a ≠ 0, all digits have logical NOT 0, so this leaves the triplets
              unaltered. If a = 0, its logical NOT is 1, so the first triplet is
              sorted as [b, c, a], leaving [[b, c, a], [d, e, f]].
      F       Flatten; yield [a, b, c, d, e, f] or [b, c, a, d, e, f].
       s2     Split into pairs; yield [[a, b], [c, d], [e, f]] or
              [[b, c], [a, d], [e, f]].
         Z    Zip; yield [[a, c, e], [b, d, f]] or [[b, a, e], [c, d, f]].
          Ḍ   Undecimal; convert each triplet from base 10 to integer.
           Ṛ  Reverse the order of the generated integers.


问:
Storing a DNS name as compactly as possible in memory (preferably in C#)
What is the most compact way to encode/save DNS names in memory?

For example, storing "www.google.com" as a string in .NET will result in the object being encoded as UTF-16, and it will consume twice as much memory as plain ASCII... but for the purpose of storing DNS names, ASCII is overkill.

The only characters that are needed are:

A..Z  (case insensitive)

0..9

Hyphen

underscore

period

Asterisk (not legal DNS, but used in ACLs such as *.google.com) always as a leading character, never elsewhere.

A total of 40 characters.. which fits within single byte with plenty room to spare.

My code golf question/challenge is what is the most compact way to store a string of characters in memory and maximizing in memory storage?

The inspiration for this challenge came from this blog entry.

答: Oh, that's easy. You just zip it.</p>

Body: Oh, that's easy. You just zip it.


问:
Find the Pisano Period
The Fibonacci sequence is a well know sequence in which each entry is the sum of the previous two and the first two entries are 1.  If we take the modulo of each term by a constant the sequence will become periodic.  For example if we took decided to compute the sequence mod 7 we would get the following:

```<code>1 1 2 3 5 1 6 0 6 6 5 4 2 6 1 0 1 1 ...
</code>```

This has a period of 16.  A related sequence, called the Pisano sequence, is defined such that a(n) is the period of the fibonacci sequence when calculated modulo n.

Task

You will should write a program or function that when given n will compute and output the period of the Fibonacci sequence mod n.  That is the nth term in the Pisano sequence.

You must only support integers on the range 0 < n < 2^30

This is a code-golf competition so you should aim to minimize the size of your source code as scored by bytes.

Test cases

```<code>1  -> 1
2  -> 3
3  -> 8
4  -> 6
5  -> 20
6  -> 24
7  -> 16
8  -> 12
9  -> 24
10 -> 60
11 -> 10
12 -> 24
</code>```

Title: Find the Pisano Period

Body:
Python, <s>188</s> <s>132</s> <s>101</s> <s>95</s> 87 characters

n=input()
s=[]
a=k=0
b=1
while s[:k]!=s[k:]or k<1:s+=[a%n];k=len(s)/2;a,b=b,a+b
print k

Usage

$ echo 10 | python pisano.py
60

For example:

$ for i in {1..50}; do; echo $i | python pisano.py; done
1
3
8
6
20
24
16
12
24
60
10
24
28
48
40
24
36
24
18
60
16
30
48
24
100
84
72
48
14
120
30
48
40
36
80
24
76
18
56
60
40
48
88
30
120
48
32
24
112
300


问:
Shortest code that return SIGSEGV among the given languages
I come across a question in a coding competion

"write  a code that returns SIGSEGV(Segmentation fault )   " .

Points were given on the basis of length of code.
The prgramming languages available  were asm,c,c++,java .

I knew c language better  and submitted my code as

```<code>   main(){char *c="h";c[3]='j';}
</code>```

But others solve it in shorter length  than me .  How it is possible ?  Can any one explain plz.

Platform UBUNTU 10.04

答:
Nah, as short as this :</p>

```<code>int main;
</code>```

OwnerDisplayName: Arya

Body:
Nah, as short as this :

int main;


问:
Print this diamond
This question has been spreading like a virus in my office. There are quite a variety of approaches:

Print the following:

```<code>        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321
 123456787654321
  1234567654321
   12345654321
    123454321
     1234321
      12321
       121
        1
</code>```

Answers are scored in characters with fewer characters being better.

答:
Raku, 42 41 38 35 chars

```<code>say " "x 9-$_,(1 x$_)²for 1…9…1
</code>```

Try it online!

Title: Print this diamond

Body:
Raku, 42 41 38 35 chars

say " "x 9-$_,(1 x$_)²for 1…9…1

Try it online!


答:
You could interpret it as a base 39 number. Since only the first character can be an asterisk, you can encode it as the sign. If i use the characters as digits in the order you named them, www.google.com would be 10903065870001232914011 in decimal and 24f0e6f41d8ecd3a65b in hex, which could be stored in 10 bytes.

*.google.com would be -310664672884413873 in decimal and fbb04c2040762a4f in hex, if you store it in 8 bytes.

Title: Storing a DNS name as compactly as possible in memory (preferably in C#)

Body:
What is the most compact way to encode/save DNS names in memory?

For example, storing "www.google.com" as a string in .NET will result in the object being encoded as UTF-16, and it will consume twice as much memory as plain ASCII... but for the purpose of storing DNS names, ASCII is overkill.

The only characters that are needed are:

A..Z  (case insensitive)

0..9

Hyphen

underscore

period

Asterisk (not legal DNS, but used in ACLs such as *.google.com) always as a leading character, never elsewhere.

A total of 40 characters.. which fits within single byte with plenty room to spare.

My code golf question/challenge is what is the most compact way to store a string of characters in memory and maximizing in memory storage?

The inspiration for this challenge came from this blog entry.


问:
Finding "sub-palindromes" 2: subsequences.
The same task as Finding "sub-palindromes" but instead of finding substrings you must find subsequences that are not substrings.

eg1:

```<code>input: "12131331"
output:
"11", "33", "111", "121", "131", "313", "333", "1111", "1331", "11311", "13331"
or
"11", "33", "111", "333", "1111", "11311", "13331"
</code>```

eg2:

```<code>input: "3333"
output:
"33", "333"
or
(null)
</code>```

Input is a string of printable ascii characters.

Output is a list of unique strings.

If a subsequence also appears as a substring it may be omitted.

Shortest code wins.

答:
Haskell (119)

```<code>import Data.List
main=interact f
f a=show.nub.filter(\x->(not$isInfixOf a x)&&x==reverse x&&length x>1)$subsequences a
</code>```

Isn't too difficult with a builtin subsequences and nub... :)

ContentLicense: CC BY-SA 2.5

Body:
Haskell (119)

import Data.List
main=interact f
f a=show.nub.filter(\x->(not$isInfixOf a x)&&x==reverse x&&length x>1)$subsequences a

Isn't too difficult with a builtin subsequences and nub... :)


答:
Mathematica 73

```<code>p = {1, 0}; j = 0; q = p;
While[j++; s = Mod[Plus @@ p, n]; p = RotateLeft@p; p[[2]] = s; p != q]; j
</code>```

Title: Find the Pisano Period

Body:
The Fibonacci sequence is a well know sequence in which each entry is the sum of the previous two and the first two entries are 1.  If we take the modulo of each term by a constant the sequence will become periodic.  For example if we took decided to compute the sequence mod 7 we would get the following:

```<code>1 1 2 3 5 1 6 0 6 6 5 4 2 6 1 0 1 1 ...
</code>```

This has a period of 16.  A related sequence, called the Pisano sequence, is defined such that a(n) is the period of the fibonacci sequence when calculated modulo n.

Task

You will should write a program or function that when given n will compute and output the period of the Fibonacci sequence mod n.  That is the nth term in the Pisano sequence.

You must only support integers on the range 0 < n < 2^30

This is a code-golf competition so you should aim to minimize the size of your source code as scored by bytes.

Test cases

```<code>1  -> 1
2  -> 3
3  -> 8
4  -> 6
5  -> 20
6  -> 24
7  -> 16
8  -> 12
9  -> 24
10 -> 60
11 -> 10
12 -> 24
</code>```

Body:
Mathematica 73

p = {1, 0}; j = 0; q = p;
While[j++; s = Mod[Plus @@ p, n]; p = RotateLeft@p; p[[2]] = s; p != q]; j


问:
Domino Effect Problem
Last week we had a programming contest in my university and I am very curious about one of the problems , one which only one team (but from another city) was able to solve. Maybe its not that hard, but I cant find any solutions that will take less than a second of execution time. The problem is the following:

Problem

You have N domino tiles separated by different amounts (integer values that are given to you) and you know the height H of these tiles (all have the same height). They are all placed standing up so that if you push one it falls in the direction of the next one. This way, if tile I is close enough (H or less) to tile I+1, the first one will push the second one when it is pushed down, producing the domino effect. Suppose that not all the distances that separate the tiles are smaller than H, what's the minimum amount of moves you need to make in order to have all the distances be at most H? You can't move the first nor the last tile. Print a falsey value if it is not possible.

Note: You are only allowed to move integer amounts and only to spots on the line defined by tile i-1 and tile i+1. This means you cant grab one and place it wherever you want.

Here are the input sizes: (3 ≤ N ≤ 1000) (1 ≤ H ≤ 50)  and the distances (1 ≤ Di ≤ 100 for i = 1, 2, ..., N-1). Someone uploaded it to SPOJ recently

Input:

N H

d1 d2 d3 d4 ... d(n-1)

Output:

Minimum amount of moves.

Sample

Input1

8 3

2 4 4 1 4 3 2

Output1

3

Sample2

Input2

10 2

1 2 2 2 2 2 2 2 3

Output2

8

Sample3

Input3

5 2

2 2 2 2

Output3

0

Sample4

Input4

5 3

1 6 2 4

Output4

-1 (NOT POSSIBLE)

I have only found a good solution for two cases (Pseudo-Code):

```<code>D=sum_of_all_distances
MaxPossible=(N-1)*H

if D==MaxPossible and there is no di such that di>H
    Answer=0

else if D>MaxPossible
    Answer=-1
</code>```

答:
Python

```<code>N, H = map(int, raw_input().split())
D = map(int, raw_input().split())

# map from (number of dominoes, distance to last domino) to
# the number of moves needed to adjust the first number of dominoes
# exactly that far.
M = {}
M[1,0] = 0

for i in xrange(2, N+1):      # i = number of dominos to try
  for d in xrange(H*(i-1)+1):
    M[i,d] = 1e9
  for d in xrange(H*(i-1)+1): # position of last domino
    for e in xrange(1, H+1):  # distance from last domino to previous one
      if d-e > H*(i-2): continue
      if d-e < 0: continue
      if sum(D[:i-1]) == d:
        # don't move last domino, arrange rest
        M[i,d] = min(M[i,d], M[i-1,d-e])
      else:
        # arrange rest, move last domino to right location
        M[i,d] = min(M[i,d], 1 + M[i-1,d-e])

print M.get((N,sum(D)), -1)
</code>```

Standard dynamic programming.  Runs pretty much instantaneously on the example inputs.  How big a problem do we have to solve in under a second?

Title: Domino Effect Problem

Body:
Python

N, H = map(int, raw_input().split())
D = map(int, raw_input().split())

# map from (number of dominoes, distance to last domino) to
# the number of moves needed to adjust the first number of dominoes
# exactly that far.
M = {}
M[1,0] = 0

for i in xrange(2, N+1):      # i = number of dominos to try
  for d in xrange(H*(i-1)+1):
    M[i,d] = 1e9
  for d in xrange(H*(i-1)+1): # position of last domino
    for e in xrange(1, H+1):  # distance from last domino to previous one
      if d-e > H*(i-2): continue
      if d-e < 0: continue
      if sum(D[:i-1]) == d:
        # don't move last domino, arrange rest
        M[i,d] = min(M[i,d], M[i-1,d-e])
      else:
        # arrange rest, move last domino to right location
        M[i,d] = min(M[i,d], 1 + M[i-1,d-e])

print M.get((N,sum(D)), -1)

Standard dynamic programming.  Runs pretty much instantaneously on the example inputs.  How big a problem do we have to solve in under a second?


问:
When does (x == x+2)?
The challenge: Define x in such a way that the expression (x == x+2) would evaluate to true.

I tagged the question with C, but answers in other languages are welcome, as long as they're creative or highlight an interesting aspect of the language.

I intend to accept a C solution, but other languages can get my vote.

Correct - works on standard-compliant implementations. Exception - assuming an implementation of the basic types, if it's a common implementation (e.g. assuming int is 32bit 2's complement) is OK.

Simple - should be small, use basic language features.

Interesting - it's subjective, I admit. I have some examples for what I consider interesting, but I don't want to give hints. Update: Avoiding the preprocessor is interesting.

Quick - The first good answer will be accepted.

After getting 60 answers (I never expected such prticipation), It may be good to summarize them.

The 60 answers divide into 7 groups, 3 of which can be implemented in C, the rest in other languages:

The C preprocessor. #define x 2|0 was suggested, but there are many other possibilities.

Floating point. Large numbers, infinity or NaN all work.

Pointer arithmetic. A pointer to a huge struct causes adding 2 to wrap around.

The rest don't work with C:

Operator overloading - A + that doesn't add or a == that always returns true.

Making x a function call (some languages allow it without the x() syntax). Then it can return something else each time.

A one-bit data type. Then x == x+2 (mod 2).

Changing 2 - some language let you assign 0 to it.

答:
Lua, used in various products including World of Warcraft, Wireshark, Nmap, Adobe Photoshop Lightroom, and the Nspire line of Texas Instruments graphing calculators, supports operator overloading (using "metamethods") for tables (associative arrays). This code works in both Lua 5.1 and 5.2:</p>

```<code>local x = setmetatable({}, {
  __add = function(a, b)
    return a
  end
})

print(x == x + 2) -- true
</code>```

Title: When does (x == x+2)?

Body:
Lua, used in various products including World of Warcraft, Wireshark, Nmap, Adobe Photoshop Lightroom, and the Nspire line of Texas Instruments graphing calculators, supports operator overloading (using "metamethods") for tables (associative arrays). This code works in both Lua 5.1 and 5.2:

local x = setmetatable({}, {
  __add = function(a, b)
    return a
  end
})

print(x == x + 2) -- true


答:
GolfScript, 24 characters

```<code>~:&1.{.2$+&%.2$(|}do](-,
</code>```

Next iteration of a GolfScript implementation. The second version now also handles 1 correctly. It became quite long but maybe someone can find a way to shorten this version. You can try above version online.

Title: Find the Pisano Period

Body:
GolfScript, 24 characters

~:&1.{.2$+&%.2$(|}do](-,

Next iteration of a GolfScript implementation. The second version now also handles 1 correctly. It became quite long but maybe someone can find a way to shorten this version. You can try above version online.


答:
Perl 6

I'm surprised to not see this solution before. Anyway, the solution is - what if x is 0 and 2 at once? my \x in this example declares sigilless variable - this question asks about x, not Perl-style $x. The ?? !! is ternary operator.

```<code>$ perl6 -e 'my \x = 0|2; say x == x + 2 ?? "YES" !! "NO"'
YES
</code>```

But...

```<code>$ perl6 -e 'my \x = 0|2; say x == x + 3 ?? "YES" !! "NO"'
NO
</code>```

x is multiple values at once. x is equal to 0 and 2 at once. x + 2 is equal to 2 and 4 at once. So, logically they're equal.

Title: When does (x == x+2)?

Body:
The challenge: Define x in such a way that the expression (x == x+2) would evaluate to true.

I tagged the question with C, but answers in other languages are welcome, as long as they're creative or highlight an interesting aspect of the language.

I intend to accept a C solution, but other languages can get my vote.

Correct - works on standard-compliant implementations. Exception - assuming an implementation of the basic types, if it's a common implementation (e.g. assuming int is 32bit 2's complement) is OK.

Simple - should be small, use basic language features.

Interesting - it's subjective, I admit. I have some examples for what I consider interesting, but I don't want to give hints. Update: Avoiding the preprocessor is interesting.

Quick - The first good answer will be accepted.

After getting 60 answers (I never expected such prticipation), It may be good to summarize them.

The 60 answers divide into 7 groups, 3 of which can be implemented in C, the rest in other languages:

The C preprocessor. #define x 2|0 was suggested, but there are many other possibilities.

Floating point. Large numbers, infinity or NaN all work.

Pointer arithmetic. A pointer to a huge struct causes adding 2 to wrap around.

The rest don't work with C:

Operator overloading - A + that doesn't add or a == that always returns true.

Making x a function call (some languages allow it without the x() syntax). Then it can return something else each time.

A one-bit data type. Then x == x+2 (mod 2).

Changing 2 - some language let you assign 0 to it.

Body:
Perl 6

I'm surprised to not see this solution before. Anyway, the solution is - what if x is 0 and 2 at once? my \x in this example declares sigilless variable - this question asks about x, not Perl-style $x. The ?? !! is ternary operator.

$ perl6 -e 'my \x = 0|2; say x == x + 2 ?? "YES" !! "NO"'
YES

But...

$ perl6 -e 'my \x = 0|2; say x == x + 3 ?? "YES" !! "NO"'
NO

x is multiple values at once. x is equal to 0 and 2 at once. x + 2 is equal to 2 and 4 at once. So, logically they're equal.


答:
PHP - <s>61</s> 57 bytes

```<code><?for(;1<$a.$b=+$a+$a=!$i+++$b%$n+=fgets(STDIN););echo$i;
</code>```

This script will erroneously report 2 for n=1, but all other values are correct.

Sample I/O, a left-truncable series where π(n) = 2n + 2 :

```<code>$ echo 3 | php pisano.php
8
$ echo 13 | php pisano.php
28
$ echo 313 | php pisano.php
628
$ echo 3313 | php pisano.php
6628
$ echo 43313 | php pisano.php
86628
$ echo 543313 | php pisano.php
1086628
$ echo 4543313 | php pisano.php
9086628
$ echo 24543313 | php pisano.php
49086628
</code>```

Title: Find the Pisano Period

Body:
PHP - <s>61</s> 57 bytes

<?for(;1<$a.$b=+$a+$a=!$i+++$b%$n+=fgets(STDIN););echo$i;

This script will erroneously report 2 for n=1, but all other values are correct.

Sample I/O, a left-truncable series where π(n) = 2n + 2 :

$ echo 3 | php pisano.php
8
$ echo 13 | php pisano.php
28
$ echo 313 | php pisano.php
628
$ echo 3313 | php pisano.php
6628
$ echo 43313 | php pisano.php
86628
$ echo 543313 | php pisano.php
1086628
$ echo 4543313 | php pisano.php
9086628
$ echo 24543313 | php pisano.php
49086628


问:
Shortest code that raises a SIGSEGV
Write the shortest code that raises a  Segmentation Fault (SIGSEGV) in any programming language.</p>

答:
C, 5 characters

```<code>main;
</code>```

It's a variable declaration - int type is implied (feature copied from B language) and 0 is default value. When executed this tries to execute a number (numbers aren't executable), and causes SIGSEGV.

Try it online!

Title: Shortest code that raises a SIGSEGV

Body:
C, 5 characters

main;

It's a variable declaration - int type is implied (feature copied from B language) and 0 is default value. When executed this tries to execute a number (numbers aren't executable), and causes SIGSEGV.

Try it online!


问:
Just Another Perl Hacker
Classic code golf challenge. Write the most obscure Perl program to print "Just another Perl hacker". Here's the Wikipedia article on it. Bonus points if it fits in 3 lines / 70 characters each.</p>

Title: Just Another Perl Hacker

Body:
eval eval '"'.

                                      ('['^"\+").(
           ('[')^                   ')').('`'|')').
        ('`'|'.').                ('['^'/').('{'^'['
 ).'\\'.'"'  .('`'^              '*').('['^'.').('['^
'(').('['^'/').('{'^            '[').('`'|'!').(('`')|
'.').('`'|'/').("\["^          '/').('`'|'(').('`'|'%'
  ).('['^')').(('{')^        '[').('{'^'+').('`'|'%').(
       '['^')').('`'|      ',').('{'^'[').('`'|'(').('`'
      |'!').('`'|'#'     ).('`'|'+').('`'|'%').('['^')').
     '\\'.'"'.("\!"^   '+').'"';$:='.'^'~';$~='@'|"\(";$^=
    ')'^'[';$/='`'|   '.';$,='('^'}';$\='`'|'!';$:=')'^"\}";
    $~='*'|"\`";$^=  '+'^'_';$/='&'|'@';$,='['&'~';$\=','^'|'
    ;$:='.'^'~';$~  ='@'|'(';$^=')'^'[';$/='`'|'.';$,='('^'}'
    ;$\='`'|'!';$:  =')'^'}';$~='*'|'`';$^='+'^'_';$/='&'|'@';
    $,='['&'~';$\=','^'|';$:='.'^'~';$~='@'|'(';$^=')'^'[';$/=
    '`'|'.';$,='('^'}';$\='`'|'!';$:=')'^'}';$~='*'|'`';$^='+'^
     '_';$/='&'|'@';$,='['&'~';$\=','^'|';$:='.'^'~';$~='@'|'('
     ;$^=')'^'[';$/='`'|'.';$,='('^'}';$\='`'|'!';$:=')'^'}';$~=
      '*'|'`';$^='+'^'_';$/='&'|'@';$,='['&'~';$\=','^'|';$:='.'^
       '~';$~='@'|'(';$^=')'^'[';$/='`'|'.';$,='('^'}';$\='`'|'!'
        ;$:=')'^'}';$~='*'|'`';$^='+'^'_';$/='&'|'@';$,="\["& '~'
         ;$\=','^'|';$:='.'^'~';$~='@'|'(';$^=')'^'[';$/='`'  |((
          '.'));$,='('^'}';$\='`'|'!';$:=')'^'}';$~ ='*'|'`'  ;$^
            ='+'^'_';$/='&'|'@';$,='['&'~';$\=','^  '|';$:=   '.'
             ^'~'; $~='@'|'(';$^=')'^'[';$/="\`"|   '.';$,=   '('
                   ^'}';$\='`'|'!';$:=')'^'}';$~    =('*')|   '`'
                   ;$^='+'^    '_';$/='&' |"\@";     $,='['   &+
                   '~';$\=     ','^'|';   $:='.'     ^"\~";  $~
                   =('@')|     "\(";$^=   "\)"^       "\[";  (
                   ($/))=      '`'|'.';   ($,)         ='('
                   ^"\}";     $\=('`')|   '!';         ($:)
                    =')'^     "\}";$~=    '*'|         '`';
                    ($^)=     '+'^'_'     ;$/=         '&'|
                    '@';     $,='['       &'~'         ;$\=
                    ','^     '|'          ;$:=         '.'^
                    '~';      $~=         '@'          |((
                    '('        ));       $^=           ')'
                    ^((         '['     ));            $/=
                    '`'          |((   '.'              ))
                    ;(             ($,))=               ((
                    ((              '('))               ))
                    ^+             "\}";$\=             ((
                   '`'            ))|+ "\!";            $:
                  =((           ')'))^  '}';           $~=
                 '*'|         "\`";$^=   '+'          ^'_'
               ;($/)=                                ('&')|
             "\@";$,=                               '['&'~'


答:
Python 90 85 96 94 90 82

```<code>n=input();c=[1,1];a=[]
while(c in a)<1%n:a+=[c];c=[c[1],sum(c)%n]
print len(a)or 1
</code>```

Edit: Implemented suggestions by beary and primo

Title: Find the Pisano Period

Body:
Python 90 85 96 94 90 82

n=input();c=[1,1];a=[]
while(c in a)<1%n:a+=[c];c=[c[1],sum(c)%n]
print len(a)or 1

Edit: Implemented suggestions by beary and primo


答:
GolfScript (28 25 24 23 chars)

```<code>~1.{(2$+}{.@+2$%}/+\-,)
</code>```

Takes input in stdin, leaves it on stdout (or the stack, if you want to further process it...)

This correctly handles the corner cases (Demo).

As a point of interest to GolfScript programmers, I think this is the first program I've written with an unfold which actually came out shorter than the other approaches I tried.

Title: Find the Pisano Period

Body:
GolfScript (28 25 24 23 chars)

~1.{(2$+}{.@+2$%}/+\-,)

Takes input in stdin, leaves it on stdout (or the stack, if you want to further process it...)

This correctly handles the corner cases (Demo).

As a point of interest to GolfScript programmers, I think this is the first program I've written with an unfold which actually came out shorter than the other approaches I tried.


答:
Python 2, <s>60</s> 59

for n in`111111111**2`:print`int('1'*int(n))**2`.center(17)
```

Abuses backticks and repunits.

Title: Print this diamond

Body:
This question has been spreading like a virus in my office. There are quite a variety of approaches:

Print the following:

```<code>        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321
 123456787654321
  1234567654321
   12345654321
    123454321
     1234321
      12321
       121
        1
</code>```

Answers are scored in characters with fewer characters being better.

Body:
Python 2, <s>60</s> 59

for n in`111111111**2`:print`int('1'*int(n))**2`.center(17)

Abuses backticks and repunits.


问:
Implementing a Traffic Light Checker
A three-color traffic light must switch lights in the following order: red, green, yellow, red.

To indicate when crossing slowly without a stop is permitted, the yellow signal may be flashed. To indicate when crossing immediately after a full stop is permitted, the red signal may be flashed.

Either flash sequence may only be started after the red light is lit and must be followed with a red. All lights are initially off. All sequences must begin a red light. Lighting any light causes all other lights to turn off.  No color may be repeated: e.g., red, red is not allowed.

Task:

Write a program that checks a sequence of light codes and determines if that sequence follows or violates the traffic light rules.

Input
Read from STDIN a sequence of the follow codes:  R (red), Y (yellow), G (Green),  P (Pause - flash red),  C (Caution - flash yellow), and X (off). Each code must be separated with a space.  The entire sequence is submitted by an end-of-line (e.g., pressing the Enter key.)  A sequence must have no more than 15 codes in total.

Winning criteria:

Output
Write to STDOUT an evaluation of the sequence:

ACCEPT     >> The entire input sequence meets all rules.

REJECT     >> The input sequence violates any sequence constraint; for example G Y.

ERROR      >> The input is malformed – undefined code, too short, too long, etc.

```
EXAMPLES:

1 - Input: R G Y R C R G Y R                  Output: ACCEPT
2 - Input: G Y R G Y R                        Output: REJECT
3 - Input: R Y G P                            Output: REJECT
4 - Input: R G Y                              Output: ERROR
5 - Input: X 8 S                              Output: ERROR
6 - Input: R G Y R C R P R G Y R G Y R G Y R  Output: ERROR
```

You do not have to worry about the reasons listed below, they are only used a reference as to why the input strings have either been Accepted, Rejected or Erroneous.

Reasons:

Correct

Doesn’t start with R

Invalid sequence

Undefined code

Undefined Codes e.g. X is not part of the grammar

The input is malformed – undefined code, too short, too long, etc.

答:
Perl, 83 chars

good grief, halfway through golfing this thing i realized its a code-challenge

```<code>$_=<>;chop;print/.{30}|[^RYGPCX ]|\S\S/?ERROR:s/^(R (C|P|G Y) )+R?$//?ACCEPT:REJECT
</code>```

Title: Implementing a Traffic Light Checker

Body:
Perl, 83 chars

good grief, halfway through golfing this thing i realized its a code-challenge

$_=<>;chop;print/.{30}|[^RYGPCX ]|\S\S/?ERROR:s/^(R (C|P|G Y) )+R?$//?ACCEPT:REJECT


问:
Turing Machine Simulator
Write a Turing machine simulator.

For simplicity we can assume statuses as integer, symbols as char, blank symbol equals whitespace

5-tuple in the form of current state, input symbol, next state, output symbol, direction (left or right) the order is not mandatory but specify if you swap it

The machine must stop when an unknown state is reached, no other halt condition allowed.

The tape is infinite in both directions and you can always read an empty character.

Input: the initial tape, an initial state and a program. you are free to read the data from anywhere in the format you like

Output: the tape after the execution of the program

Required: an example program that run on top of your simulator

This is a code-colf so the shortest code win.

I'll post an implementation and some example programs in the next few hours.

答:
Python, 101 189 152 142

```<code>a=dict(zip(range(len(b)),b))
r=eval(p)
i=s=0
while 1:
 c=a.get(i,' ')
 s,m,a[i]=r[s,c]
 if 0==m:exit([x[1]for x in sorted(a.items())])
 i=i+m
</code>```

b and p are the inputs, b is the initial tape, p encodes the rules as (string representation of) a dict from (in-state, in-tape) tuple to (out-state, head move, out-tape) tuple. If move is 0 the program finishes, 1 is move to the right and -1 is move to the left.

```<code>b="aaba"

p="""{(0, 'a'): (1, 1, 'a'),
      (0, 'b'): (0, 1, 'b'),
      (1, 'a'): (1, 1, 'a'),
      (1, 'b'): (0, 1, 'b'),
      (1, ' '): (1, 0, 'Y'),
      (0, ' '): (0, 0, 'N')}"""
</code>```

This sample program tests if the last letter of the string (before empty tape) is 'a', if so it writes 'Y' at the end of the string (first empty space).

Edit 1:

Changed the tape to be represented as a dict, as it seemed the shortest way to write an extensible data structure. The second to last line is mostly transforming it back into readable form for output.

Edit 2:

Thanks to Strigoides for a great deal of improvements.

Edit 3:

I had unnecessarily made it so 0 as output would leave the place as it is.
I removed this as we can always write the output the same as the input.

Title: Turing Machine Simulator

Body:
Python, 101 189 152 142

a=dict(zip(range(len(b)),b))
r=eval(p)
i=s=0
while 1:
 c=a.get(i,' ')
 s,m,a[i]=r[s,c]
 if 0==m:exit([x[1]for x in sorted(a.items())])
 i=i+m

b and p are the inputs, b is the initial tape, p encodes the rules as (string representation of) a dict from (in-state, in-tape) tuple to (out-state, head move, out-tape) tuple. If move is 0 the program finishes, 1 is move to the right and -1 is move to the left.

b="aaba"

p="""{(0, 'a'): (1, 1, 'a'),
      (0, 'b'): (0, 1, 'b'),
      (1, 'a'): (1, 1, 'a'),
      (1, 'b'): (0, 1, 'b'),
      (1, ' '): (1, 0, 'Y'),
      (0, ' '): (0, 0, 'N')}"""

This sample program tests if the last letter of the string (before empty tape) is 'a', if so it writes 'Y' at the end of the string (first empty space).

Edit 1:

Changed the tape to be represented as a dict, as it seemed the shortest way to write an extensible data structure. The second to last line is mostly transforming it back into readable form for output.

Edit 2:

Thanks to Strigoides for a great deal of improvements.

Edit 3:

I had unnecessarily made it so 0 as output would leave the place as it is.
I removed this as we can always write the output the same as the input.


Title: Turing Machine Simulator

Body:
Write a Turing machine simulator.

For simplicity we can assume statuses as integer, symbols as char, blank symbol equals whitespace

5-tuple in the form of current state, input symbol, next state, output symbol, direction (left or right) the order is not mandatory but specify if you swap it

The machine must stop when an unknown state is reached, no other halt condition allowed.

The tape is infinite in both directions and you can always read an empty character.

Input: the initial tape, an initial state and a program. you are free to read the data from anywhere in the format you like

Output: the tape after the execution of the program

Required: an example program that run on top of your simulator

This is a code-colf so the shortest code win.

I'll post an implementation and some example programs in the next few hours.

Body:
Groovy <s>234</s> <s>228</s> <s>154</s> <s>153</s> <s>149</s> <s>139</s> 124

n=[:];i=0;t={it.each{n[i++]=it};i=0};e={p,s->a=p[s,n[i]?:' '];if(a){n[i]=a[1];i+=a[2];e(p,a[0])}else n.sort()*.value.join()}

Formatted for readability

n=[:];
i=0;
t={it.each{n[i++]=it};i=0};
e={p,s->
    a=p[s,n[i]?:' '];
    if(a){
        n[i]=a[1];
        i+=a[2];
        e(p,a[0])
    }else n.sort()*.value.join()
}

t is the function that set the tape
e is the function that evaluate the program

Example 1 - Print "Hello!" on the tape :)

t('')
e([[0,' ']:[1,'H',1],
   [1,' ']:[2,'e',1],
   [2,' ']:[3,'l',1],
   [3,' ']:[4,'l',1],
   [4,' ']:[5,'o',1],
   [5,' ']:[6,'!',1]],0)

Example 2 - Leave a T on the tape if the initial string is in the form of anbn, stop otherwise.

t('aaabbb')
e([[0,'a']:[1,' ',1],
   [0,' ']:[4,' ',1],
   [1,'a']:[1,'a',1],
   [1,'b']:[1,'b',1],
   [1,' ']:[2,' ',-1],
   [2,'b']:[3,' ',-1],
   [2,'a']:[5,'a',-1],
   [3,'b']:[3,'b',-1],
   [3,'a']:[3,'a',-1],
   [3,' ']:[0,' ',1],
   [4,' ']:[5,'T',1]],0)

Example 3 - Increment of a binary number

t('101')
e([[0,'0']:[0,'0',1],
   [0,'1']:[0,'1',1],
   [0,' ']:[1,' ',-1],
   [1,'0']:[2,'1',1],
   [1,'1']:[3,'0',-1],
   [3,'0']:[2,'1',1],
   [3,' ']:[2,'1',1],
   [3,'1']:[3,'0',-1]],0)

in the examples 1 means move to the right and -1 means move to the left


问:
Power modulo golf.
Write a function f(a,b,c) that calculates a^b (mod c) in less than 10 seconds.

a, b < 10^100

c < 10000.

examples:

```<code>f(10^50, 10^50, 54123) = 46555
f(5^99, 10^99, 777) = 1
</code>```

答:
Haskell, 65

Takes the liberty of taking the modulus only on set bits of binary b, but given the range constraints that won't be a problem.

```<code>f a b c|b==0=1|odd b=mod(a*f a(b-1)c)c|0<1=f(mod(a^2)c)(div b 2)c
</code>```

Title: Power modulo golf.

Body:
Haskell, 65

Takes the liberty of taking the modulus only on set bits of binary b, but given the range constraints that won't be a problem.

f a b c|b==0=1|odd b=mod(a*f a(b-1)c)c|0<1=f(mod(a^2)c)(div b 2)c


答:
Scala - 86 characters

```<code>val a="543210/.-./012345";for(i<-a){for(j<-a;k=99-i-j)print(if(k<1)" "else k);println}
</code>```

Title: Print this diamond

Body:
Scala - 86 characters

val a="543210/.-./012345";for(i<-a){for(j<-a;k=99-i-j)print(if(k<1)" "else k);println}