问:
Rainbowlify An Image
This challenge is about gradually shifting hues in an image to make pretty pictures like this:

(original)

Challenge

Write a program or function that takes in two non-negative integers and an image in any common image file format of your choosing (you can take a path to the image or the raw image data).

We'll call the first integer the cycles and the second integer the offset.

We'll also define floating-point step as 360 times cycles divided by the area of the image, or step = 360 * cycles / (image width * image height).

For each pixel P in the image, moving one row at a time, left-to-right, top-to-bottom (i.e. in reading order if the pixels were letters), do the following:

Increase the hue of P by offset degrees (looping around from 360 to 0 if necessary).

Then increase offset by step.

Save, display, or output raw the resulting image in any common image file format.

This procedure incrementally increases the hue of all the pixels in the image, making cycles full loops around the hue rainbow, starting by initially offsetting the hue by offset.

When cycles is 1 and offset is 0, as in the Starry Night image above, the top and bottom rows of pixels have practically no hue shift but in between there's a full color cycle.

Details

Cycles can be any non-negative integer but you may assume that offset is from 0 to 359 inclusive.

When cycles is 0, every pixel in the image will have its hue shifted by exactly offset since step must be 0 too. (In this case if offset is 0 then the image doesn't change at all.)

You may assume cycles and offset are input as floats if desired (i.e. 1.0 instead of 1). (I realize they needn't be integers at all, it just makes the challenge simpler.)

"Hue" refers to the RGB color space version, common in HSL/HSV color models.

Examples

Original:

Cycles = 1, offset = 0:

Cycles = 1, offset = 180:

Original:

Cycles = 2, offset = 60:

Original:

(Thanks ArtOfCode.)

Cycles = 1, offset = 120:

Original:

(Thanks Doorknob.)

Cycles = 1, offset = 0:

Cycles = 4, offset = 0:

Cycles = 200, offset = 0:

Cycles = 30000, offset = 0:

(These images may not be pixel perfect due to imgur compressing them.)

Scoring

The shortest code in bytes wins. Tiebreaker is higher voted answer.

Answers that post their own cool looking test images will get more brownie points from me.

答:
Java (Full program), 491 488 bytes (Thanks @Geobits)

```<code>import java.awt.*;import java.io.*;import static javax.imageio.ImageIO.*;class Q{public static void main(String[]v)throws Exception{File f=new File(v[2]);java.awt.image.BufferedImage b=read(f);for(int i=0,j,h=b.getHeight(),w=b.getWidth();i<h;i++)for(j=0;j<w;){Color c=new Color(b.getRGB(j,i));float[]a=new float[3];c.RGBtoHSB(c.getRed(),c.getGreen(),c.getBlue(),a);b.setRGB(j++,i,c.HSBtoRGB((a[0]+Float.valueOf(v[1])/360+(i*w+j)*Float.valueOf(v[0])/w/h)%1,a[1],a[2]));}write(b,"png",f);}}
</code>```

Ungolfed

```<code>import java.awt.*;
import java.io.*;

import static javax.imageio.ImageIO.*;

class A79200 {
    public static void main(String[] v) throws Exception {
        File file = new File(v[2]);
        java.awt.image.BufferedImage image = read(file);
        for (int i = 0, j, height = image.getHeight(), width = image.getWidth(); i < height; i++)
            for (j = 0; j < width; ) {
                Color color = new Color(image.getRGB(j, i));
                float[] arr = new float[3];
                color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), arr);
                image.setRGB(j++, i, color.HSBtoRGB((arr[0] + Float.valueOf(v[1]) / 360 + (i * width + j) * Float.valueOf(v[0]) / width / height) % 1, arr[1], arr[2]));
            }
        write(image, "png", file);
    }
}
</code>```

Explanation

Usage: Pretty straightforward. Compile with java -c Q.java. Run with java Q <cycles> <offset> <imagepath>. Will override the existing image, so be careful.

I was gonna make a method only solution at first but I didn't quite know how to handle imports on those, so I figured I'd go full java, this is probably not going to win anyways :^)

Results:

Image 1: 1 cycle, 0 offset

Image 1: 1 cycle, 180 offset

Image 2: 2 cycles, 60 offset

Image 3: 1 cycle, 120 offset

Image 4: 1 cycle, 0 offset

Image 4: 4 cycles, 0 offset

Image 4: 200 cycles, 0 offset

Bonus: The Starry Night, 1 cycle, 0 offset

Title: Rainbowlify An Image

Body:
Java (Full program), 491 488 bytes (Thanks @Geobits)

import java.awt.*;import java.io.*;import static javax.imageio.ImageIO.*;class Q{public static void main(String[]v)throws Exception{File f=new File(v[2]);java.awt.image.BufferedImage b=read(f);for(int i=0,j,h=b.getHeight(),w=b.getWidth();i<h;i++)for(j=0;j<w;){Color c=new Color(b.getRGB(j,i));float[]a=new float[3];c.RGBtoHSB(c.getRed(),c.getGreen(),c.getBlue(),a);b.setRGB(j++,i,c.HSBtoRGB((a[0]+Float.valueOf(v[1])/360+(i*w+j)*Float.valueOf(v[0])/w/h)%1,a[1],a[2]));}write(b,"png",f);}}

Ungolfed

import java.awt.*;
import java.io.*;

import static javax.imageio.ImageIO.*;

class A79200 {
    public static void main(String[] v) throws Exception {
        File file = new File(v[2]);
        java.awt.image.BufferedImage image = read(file);
        for (int i = 0, j, height = image.getHeight(), width = image.getWidth(); i < height; i++)
            for (j = 0; j < width; ) {
                Color color = new Color(image.getRGB(j, i));
                float[] arr = new float[3];
                color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), arr);
                image.setRGB(j++, i, color.HSBtoRGB((arr[0] + Float.valueOf(v[1]) / 360 + (i * width + j) * Float.valueOf(v[0]) / width / height) % 1, arr[1], arr[2]));
            }
        write(image, "png", file);
    }
}

Explanation

Usage: Pretty straightforward. Compile with java -c Q.java. Run with java Q <cycles> <offset> <imagepath>. Will override the existing image, so be careful.

I was gonna make a method only solution at first but I didn't quite know how to handle imports on those, so I figured I'd go full java, this is probably not going to win anyways :^)

Results:

Image 1: 1 cycle, 0 offset

Image 1: 1 cycle, 180 offset

Image 2: 2 cycles, 60 offset

Image 3: 1 cycle, 120 offset

Image 4: 1 cycle, 0 offset

Image 4: 4 cycles, 0 offset

Image 4: 200 cycles, 0 offset

Bonus: The Starry Night, 1 cycle, 0 offset


问:
Counting triangles with integer perimeter
Mary has given John two sticks of lengths a and b respectively, where a and b are positive integers.

John is very curious.

He would like to know how many triangles with integer perimeter can be formed, by having one additional side.

Please help him find it out.

(This is my first time composing this kind of stupid stories in coding problems, so forgive me if it is too stupid.)

Specs

Given two integers a and b, find the number of triangles with integer perimeter that can be formed, by having one additional side.

Details

Congruent triangles are congruent.

Flat triangles are flat out uncounted.

Zero-sided triangles are counted zero times.

Scoring

This is code-golf. Shortest solution in bytes wins.

Testcases

```<code>a b output
1 2 1
3 3 5
9 7 13
</code>```

答:
Cubix, 18 <s>19</s> bytes

Not overly short, but a tad more interesting to do due to a lack of a minimum function.
Saved a byte with a big thanks to Martin Büttner

```<code>-@IOIU>wu+..U;?;2*
</code>```

This wraps onto a cube with edge length 2 and ends up looking like this

```<code>    - @
    I O
I U > w u + . .
U ; ? ; 2 * . .
    . .
    . .
</code>```

Explanation that hopefully can be followed. Try it here

Getting parameters from STDIN

```<code>    -                # This section gets input, u-turns onto top face,
    I                # heading up, gets another input and performs a subtraction.
I U                  # Carries on around the bottom of the cube upto the next part.
</code>```

Determine least and leaving it at TOS

```<code>    > w              # Hits the ? going up.  if TOS is negative turn left, pop stack
U ; ? ;              # and U-turn onto bottom face heading back up to ?.
    .                # If 0 redirect through > and w to ; popping stack, heading right.
    .                # If positive redirect right to ; which pops TOS
</code>```

Output the answer and end

```<code>      @              # Push 2 onto the stack, multiply, U-turn onto input which
      O              # gives us -1 for the stack, add it then u-turn to the left
I       u +          # onto the top face, output the TOS as number and end
U       2 *

</code>```

ContentLicense: CC BY-SA 3.0

Body:
Cubix, 18 <s>19</s> bytes

Not overly short, but a tad more interesting to do due to a lack of a minimum function.
Saved a byte with a big thanks to Martin Büttner

-@IOIU>wu+..U;?;2*

This wraps onto a cube with edge length 2 and ends up looking like this

    - @
    I O
I U > w u + . .
U ; ? ; 2 * . .
    . .
    . .

Explanation that hopefully can be followed. Try it here

Getting parameters from STDIN

    -                # This section gets input, u-turns onto top face,
    I                # heading up, gets another input and performs a subtraction.
I U                  # Carries on around the bottom of the cube upto the next part.

Determine least and leaving it at TOS

    > w              # Hits the ? going up.  if TOS is negative turn left, pop stack
U ; ? ;              # and U-turn onto bottom face heading back up to ?.
    .                # If 0 redirect through > and w to ; popping stack, heading right.
    .                # If positive redirect right to ; which pops TOS

Output the answer and end

      @              # Push 2 onto the stack, multiply, U-turn onto input which
      O              # gives us -1 for the stack, add it then u-turn to the left
I       u +          # onto the top face, output the TOS as number and end
U       2 *


答:
Pyth, 86 bytes, full program

```<code>=N.tE7=Z*6*.n0cEl.n'zMmhtS[0255ss*VG.>+Lc-1.tH1 3[.tH1Kc.tH0@3 2_K)d)3.wmmgk~-NZd'z
</code>```

Pyth doesn't have built-in color space conversions - this is the real deal.

Takes input in the following format on stdin:

```<code>input_filename.png
offset
cycles
</code>```

The output image is written to o.png.

This works by rotating the color cube around its diagonal, and then clamping any values outside of the range.

If a is the angle to rotate by, and r, g, b is the input color, we calculate the new color r', g', b' by:

```<code>o = cos(a), i = sin(a) / sqrt(3)
n = (1 - o) / 3
m = [n + o, n - i, n + i]
clamp(c) = max(0, min(255, c))
r' = clamp(r*m[0] + g*m[1] + b*m[2])
g' = clamp(r*m[2] + g*m[0] + b*m[1])
b' = clamp(r*m[1] + g*m[2] + b*m[0])
</code>```

Title: Rainbowlify An Image

Body:
This challenge is about gradually shifting hues in an image to make pretty pictures like this:

(original)

Challenge

Write a program or function that takes in two non-negative integers and an image in any common image file format of your choosing (you can take a path to the image or the raw image data).

We'll call the first integer the cycles and the second integer the offset.

We'll also define floating-point step as 360 times cycles divided by the area of the image, or step = 360 * cycles / (image width * image height).

For each pixel P in the image, moving one row at a time, left-to-right, top-to-bottom (i.e. in reading order if the pixels were letters), do the following:

Increase the hue of P by offset degrees (looping around from 360 to 0 if necessary).

Then increase offset by step.

Save, display, or output raw the resulting image in any common image file format.

This procedure incrementally increases the hue of all the pixels in the image, making cycles full loops around the hue rainbow, starting by initially offsetting the hue by offset.

When cycles is 1 and offset is 0, as in the Starry Night image above, the top and bottom rows of pixels have practically no hue shift but in between there's a full color cycle.

Details

Cycles can be any non-negative integer but you may assume that offset is from 0 to 359 inclusive.

When cycles is 0, every pixel in the image will have its hue shifted by exactly offset since step must be 0 too. (In this case if offset is 0 then the image doesn't change at all.)

You may assume cycles and offset are input as floats if desired (i.e. 1.0 instead of 1). (I realize they needn't be integers at all, it just makes the challenge simpler.)

"Hue" refers to the RGB color space version, common in HSL/HSV color models.

Examples

Original:

Cycles = 1, offset = 0:

Cycles = 1, offset = 180:

Original:

Cycles = 2, offset = 60:

Original:

(Thanks ArtOfCode.)

Cycles = 1, offset = 120:

Original:

(Thanks Doorknob.)

Cycles = 1, offset = 0:

Cycles = 4, offset = 0:

Cycles = 200, offset = 0:

Cycles = 30000, offset = 0:

(These images may not be pixel perfect due to imgur compressing them.)

Scoring

The shortest code in bytes wins. Tiebreaker is higher voted answer.

Answers that post their own cool looking test images will get more brownie points from me.

Body:
Pyth, 86 bytes, full program

=N.tE7=Z*6*.n0cEl.n'zMmhtS[0255ss*VG.>+Lc-1.tH1 3[.tH1Kc.tH0@3 2_K)d)3.wmmgk~-NZd'z

Pyth doesn't have built-in color space conversions - this is the real deal.

Takes input in the following format on stdin:

input_filename.png
offset
cycles

The output image is written to o.png.

This works by rotating the color cube around its diagonal, and then clamping any values outside of the range.

If a is the angle to rotate by, and r, g, b is the input color, we calculate the new color r', g', b' by:

o = cos(a), i = sin(a) / sqrt(3)
n = (1 - o) / 3
m = [n + o, n - i, n + i]
clamp(c) = max(0, min(255, c))
r' = clamp(r*m[0] + g*m[1] + b*m[2])
g' = clamp(r*m[2] + g*m[0] + b*m[1])
b' = clamp(r*m[1] + g*m[2] + b*m[0])


问:
Compute the Adler-32 checksum

Background

Adler-32 is a 32-bit checksum invented by Mark Adler in 1995 which is part of the widely used zlib library (also developed by Adler). Adler-32 is not as reliable as a 32-bit cyclic redundancy check, but – at least in software  – it is much faster and easier to implement.

Definition

Let B = [b1, ⋯, bn] be a byte array.

The Adler-32 checksum of B is defined as the result of low + 65536 × high, where:

low := ((1 + b1 + ⋯ + bn) mod 65521)

high := (((1 + b1) + (1 + b1 + b2) + ⋯ (1 + b1 + ⋯ + bn)) mod 65521)

Task

Given a byte array as input, compute and return its Adler-32 checksum, abiding to the following.

You can take the input as an array of bytes or integers, or as a string.

In both cases, only bytes corresponding to printable ASCII characters will occur in the input.

You may assume that the length of the input will satisfy 0 < length ≤ 4096.

If you choose to print the output, you may use any positive base up to and including 256.

If you choose unary, make sure interpreter can handle up to 232 - 983056 bytes of output on a machine with 16 GiB of RAM.

Built-ins that compute the Adler-32 checksum are forbidden.

Standard code-golf rules apply.

Test cases

```<code>String:     "Eagles are great!"
Byte array: [69, 97, 103, 108, 101, 115, 32, 97, 114, 101, 32, 103, 114, 101, 97, 116, 33]
Checksum:   918816254

String:     "Programming Puzzles & Code Golf"
Byte array: [80, 114, 111, 103, 114, 97, 109, 109, 105, 110, 103, 32, 80, 117, 122, 122, 108, 101, 115, 32, 38, 32, 67, 111, 100, 101, 32, 71, 111, 108, 102]
Checksum:   3133147946

String:     "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
Byte array: [126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126]
Checksum:   68095937

String:     <1040 question marks>
Byte array: <1040 copies of 63>
Checksum:   2181038080
</code>```

答:
ARM Thumb-2 function accepting uint8_t[]: 40 bytes (36B for non-standard ABI and int[])

Features: non-deferred modulo, so arbitrary-size inputs are fine.  Doesn't actually use the division instruction, so it's not slow.  (err, at least not for that reason :P)

Savings from following less strict rules:

-2B if we don't have to save registers before using them.

-2B for requiring the caller to unpack bytes into a uint32_t[] array.

So, best-case is 36B.

```<code>// uint8_t *buf in r0,  uint32_t len in r1
00000000 <adler32arm_golf2>:
   0:   b570            push    {r4, r5, r6, lr} //
   2:   2201            movs    r2, #1          // low
   4:   2300            movs    r3, #0          // high
   6:   f64f 75f1       movw    r5, #65521      ; 0xfff1 = m
0000000a <adler32arm_golf2.byteloop>:
   a:   f810 4b01       ldrb.w  r4, [r0], #1    // post-increment byte-load
   e:   4422            add     r2, r4          // low += *B
  10:   4413            add     r3, r2          // high += low
  12:   42aa            cmp     r2, r5          // subtract if needed instead of deferred modulo
  14:   bf28            it      cs
  16:   1b52            subcs   r2, r2, r5
  18:   42ab            cmp     r3, r5
  1a:   bf28            it      cs              // Predication in thumb mode is still possible, but takes a separate instruction
  1c:   1b5b            subcs   r3, r3, r5
  1e:   3901            subs    r1, #1          // while(--len)
  20:   d1f3            bne.n   a <.byteloop2>
  22:   eac2 4003       pkhbt   r0, r2, r3, lsl #16   // other options are the same size: ORR or ADD.
  26:   bd70            pop     {r4, r5, r6, pc}  // ARM can return by popping the return address (from lr) into the pc; nifty
00000028 <adler32arm_end_golf2>:
</code>```

0x28 = 40 bytes

Notes:

Instead of log%m at the end, we do if(low>=m) low-=m inside the loop.  If we do low before high, we know that neither can possibly exceed 2*m, so modulo is just a matter of subtracting or not.  A cmp and predicated sub is only 6B in Thumb2 mode.  The standard idiom for % is 8B in Thumb2 mode:

```<code>UDIV R2, R0, R1         // R2 <- R0 / R1
MLS  R0, R1, R2, R0     // R0 <- R0 - (R1 * R2 )
</code>```

The implicit-length adler(char *) version is the same code-size as the explicit length adler(uint8_t[], uint32_t len).  We can set flags for the loop-exit condition with a single 2B instruction either way.

The implicit-length version has the advantage of working correctly with the empty string, instead of trying to loop 2^32 times.

assemble / compile with:

```<code>arm-linux-gnueabi-as --gen-debug -mimplicit-it=always -mfloat-abi=soft -mthumb adler32-arm.S
</code>```

or

```<code>arm-linux-gnueabi-g++ -Wa,-mimplicit-it=always -g -static -std=gnu++14 -Wall -Wextra -Os -march=armv6t2 -mthumb -mfloat-abi=soft test-adler32.cpp -fverbose-asm adler32-arm.S -o test-adler32
qemu-arm ./test-adler32
</code>```

Without -static, the process running under qemu-arm didn't find it's dynamic linker.  (And yes, I install an ARM cross-devel setup just for this answer, because I thought my predicated-subtract idea was neat.)  On amd64 Ubuntu, install gcc-arm-linux-gnueabi, g++-arm-linux-gnueabi.  I found gdb-arm-none-eabi sort of barely worked connecting to qemu-arm -g port.

Commented source:

```<code>// There's no directive to enable implicit-it=always

// gcc uses compiler uses these in its output
.syntax unified
.arch armv8-a
.fpu softvfp

.thumb      @ aka .code 16

.p2align 4
.globl adler32arm_golf    @ put this label on the one we want to test

.thumb_func
adler32arm_golf:
adler32arm_golf2:   @ (uint8_t buf[], uint32_t len)
        @ r0 = buf
        @ r1 = len
        push    {r4, r5, r6, lr}   @ even number of regs keeps the stack aligned.  Good style? since there's no code-size saving

        movs    r2, #1          @ r2: low
        movs    r3, #0          @ r3: high
                                @ r4 = tmp for loading bytes
        movw    r5, #65521      @ r5: modulo constant

adler32arm_golf2.byteloop2:
        ldrb    r4, [r0], #1    @ *(buf++) post-increment addressing.  4B encoding
        @ldrb    r4, [r0, r1]   @ 2B encoding, but unless we make the caller pass us buf+len and -len, it needs extra code somewhere else
        @ldmia   r0!, {r4}      @ int[] version:  r4 = [r0]; r0+=4;  post-increment addressing.  2B encoding.

        add     r2, r2, r4      @ low += tmp
        add     r3, r3, r2      @ high += low;   // I think it's safe to do this before the modulo range-reduction for low, but it would certainly work to put it after.

        cmp     r2, r5
        subhs   r2, r5          @ if(low>=m) low-=m;   @ 6B total for %.  predicated insns require an IT instruction in thumb2

        cmp     r3, r5
        subhs   r3, r5          @ if(high>=m) high-=m;  // equivalent to high %= m.

        @sub    r1, #1          @ 4B encoding: sub.w to not set flags with immediate
        subs    r1, #1          @ len-- and set flags.  2B encoding
        @cmp    r4, #0          @ null-termination check. 2B encoding
        bne     adler32arm_golf2.byteloop2

@        udiv    r0, r2, r5            @ normal way to do one of the modulos
@        mls     r2, r5, r0, r2         @ r2 = low % m.  8B total for %

        PKHBT   r0, r2, r3, lsl #16     @ 4B   r0 = [ high%m <<16  |   low%m  ]
        @orr     r0, r0, r4, lsl #16    @ 4B
        @orr     r0, r0, r4             @ 4B
        @add     r0, r2, r3, lsl #16    @ 4B
        @add     r0, r0, r4             @ 2B
        pop     {r4, r5, r6, pc}        @ ARM can return by popping the return address (saved from lr) into pc.  Nifty
adler32arm_end_golf2:
</code>```

test-adler32.cpp has the same test-cases and main() as for my x86-64 answer, but starts this way:

#include <stdint.h>
uint32_t adler32_simple(const uint8_t *B) {
  const uint32_t m=65521;

  uint32_t h=0, l=1;
  do {
    l += *B++;        // Borrowed from orlp's answer, as a simple reference implementation
    h += l;
    l %= m; h %= m;   // with non-deferred modulo if this is uncommented
  } while(*B);

  return h%m<<16|l%m;
}

#include <stdio.h>
//#include <zlib.h>
#include <string.h>
#include <assert.h>
#include <string>   // useful for the memset-style constructors that repeat a character n times

extern "C" {
    unsigned golfed_adler32_amd64(int /*dummy1*/, const char *buf, int /*dummy2*/, unsigned len);
    unsigned adler32arm_golf(const char *buf, unsigned len);
}
#ifdef __amd64__
#define golfed_adler32(buf, len)   golfed_adler32_amd64(1234, buf, 1234, len)
#elif  __arm__
#define golfed_adler32(buf, len)   adler32arm_golf(buf, len)
#else
#error "no architecture"
#endif

static void test_adler(const char *str)
{
    unsigned len = strlen(str);
//    unsigned zlib = zlib_adler(len, str);
    unsigned reference = adler32_simple((const uint8_t*)str);
    unsigned golfed = golfed_adler32(str, len);

    printf("%s: c:%u asm:%u\n", str, reference, golfed);
    assert(reference == golfed);
}

// main() to call test_adler() unchanged from my amd64 answer, except that the comments about length limits don't apply
```

Title: Compute the Adler-32 checksum

Body:
ARM Thumb-2 function accepting uint8_t[]: 40 bytes (36B for non-standard ABI and int[])

Features: non-deferred modulo, so arbitrary-size inputs are fine.  Doesn't actually use the division instruction, so it's not slow.  (err, at least not for that reason :P)

Savings from following less strict rules:

-2B if we don't have to save registers before using them.

-2B for requiring the caller to unpack bytes into a uint32_t[] array.

So, best-case is 36B.

// uint8_t *buf in r0,  uint32_t len in r1
00000000 <adler32arm_golf2>:
   0:   b570            push    {r4, r5, r6, lr} //
   2:   2201            movs    r2, #1          // low
   4:   2300            movs    r3, #0          // high
   6:   f64f 75f1       movw    r5, #65521      ; 0xfff1 = m
0000000a <adler32arm_golf2.byteloop>:
   a:   f810 4b01       ldrb.w  r4, [r0], #1    // post-increment byte-load
   e:   4422            add     r2, r4          // low += *B
  10:   4413            add     r3, r2          // high += low
  12:   42aa            cmp     r2, r5          // subtract if needed instead of deferred modulo
  14:   bf28            it      cs
  16:   1b52            subcs   r2, r2, r5
  18:   42ab            cmp     r3, r5
  1a:   bf28            it      cs              // Predication in thumb mode is still possible, but takes a separate instruction
  1c:   1b5b            subcs   r3, r3, r5
  1e:   3901            subs    r1, #1          // while(--len)
  20:   d1f3            bne.n   a <.byteloop2>
  22:   eac2 4003       pkhbt   r0, r2, r3, lsl #16   // other options are the same size: ORR or ADD.
  26:   bd70            pop     {r4, r5, r6, pc}  // ARM can return by popping the return address (from lr) into the pc; nifty
00000028 <adler32arm_end_golf2>:

0x28 = 40 bytes

Notes:

Instead of log%m at the end, we do if(low>=m) low-=m inside the loop.  If we do low before high, we know that neither can possibly exceed 2*m, so modulo is just a matter of subtracting or not.  A cmp and predicated sub is only 6B in Thumb2 mode.  The standard idiom for % is 8B in Thumb2 mode:

UDIV R2, R0, R1         // R2 <- R0 / R1
MLS  R0, R1, R2, R0     // R0 <- R0 - (R1 * R2 )

The implicit-length adler(char *) version is the same code-size as the explicit length adler(uint8_t[], uint32_t len).  We can set flags for the loop-exit condition with a single 2B instruction either way.

The implicit-length version has the advantage of working correctly with the empty string, instead of trying to loop 2^32 times.

assemble / compile with:

arm-linux-gnueabi-as --gen-debug -mimplicit-it=always -mfloat-abi=soft -mthumb adler32-arm.S

or

arm-linux-gnueabi-g++ -Wa,-mimplicit-it=always -g -static -std=gnu++14 -Wall -Wextra -Os -march=armv6t2 -mthumb -mfloat-abi=soft test-adler32.cpp -fverbose-asm adler32-arm.S -o test-adler32
qemu-arm ./test-adler32

Without -static, the process running under qemu-arm didn't find it's dynamic linker.  (And yes, I install an ARM cross-devel setup just for this answer, because I thought my predicated-subtract idea was neat.)  On amd64 Ubuntu, install gcc-arm-linux-gnueabi, g++-arm-linux-gnueabi.  I found gdb-arm-none-eabi sort of barely worked connecting to qemu-arm -g port.

Commented source:

// There's no directive to enable implicit-it=always

// gcc uses compiler uses these in its output
.syntax unified
.arch armv8-a
.fpu softvfp

.thumb      @ aka .code 16

.p2align 4
.globl adler32arm_golf    @ put this label on the one we want to test

.thumb_func
adler32arm_golf:
adler32arm_golf2:   @ (uint8_t buf[], uint32_t len)
        @ r0 = buf
        @ r1 = len
        push    {r4, r5, r6, lr}   @ even number of regs keeps the stack aligned.  Good style? since there's no code-size saving

        movs    r2, #1          @ r2: low
        movs    r3, #0          @ r3: high
                                @ r4 = tmp for loading bytes
        movw    r5, #65521      @ r5: modulo constant

adler32arm_golf2.byteloop2:
        ldrb    r4, [r0], #1    @ *(buf++) post-increment addressing.  4B encoding
        @ldrb    r4, [r0, r1]   @ 2B encoding, but unless we make the caller pass us buf+len and -len, it needs extra code somewhere else
        @ldmia   r0!, {r4}      @ int[] version:  r4 = [r0]; r0+=4;  post-increment addressing.  2B encoding.

        add     r2, r2, r4      @ low += tmp
        add     r3, r3, r2      @ high += low;   // I think it's safe to do this before the modulo range-reduction for low, but it would certainly work to put it after.

        cmp     r2, r5
        subhs   r2, r5          @ if(low>=m) low-=m;   @ 6B total for %.  predicated insns require an IT instruction in thumb2

        cmp     r3, r5
        subhs   r3, r5          @ if(high>=m) high-=m;  // equivalent to high %= m.

        @sub    r1, #1          @ 4B encoding: sub.w to not set flags with immediate
        subs    r1, #1          @ len-- and set flags.  2B encoding
        @cmp    r4, #0          @ null-termination check. 2B encoding
        bne     adler32arm_golf2.byteloop2

@        udiv    r0, r2, r5            @ normal way to do one of the modulos
@        mls     r2, r5, r0, r2         @ r2 = low % m.  8B total for %

        PKHBT   r0, r2, r3, lsl #16     @ 4B   r0 = [ high%m <<16  |   low%m  ]
        @orr     r0, r0, r4, lsl #16    @ 4B
        @orr     r0, r0, r4             @ 4B
        @add     r0, r2, r3, lsl #16    @ 4B
        @add     r0, r0, r4             @ 2B
        pop     {r4, r5, r6, pc}        @ ARM can return by popping the return address (saved from lr) into pc.  Nifty
adler32arm_end_golf2:

test-adler32.cpp has the same test-cases and main() as for my x86-64 answer, but starts this way:

#include <stdint.h>
uint32_t adler32_simple(const uint8_t *B) {
  const uint32_t m=65521;

  uint32_t h=0, l=1;
  do {
    l += *B++;        // Borrowed from orlp's answer, as a simple reference implementation
    h += l;
    l %= m; h %= m;   // with non-deferred modulo if this is uncommented
  } while(*B);

  return h%m<<16|l%m;
}

#include <stdio.h>
//#include <zlib.h>
#include <string.h>
#include <assert.h>
#include <string>   // useful for the memset-style constructors that repeat a character n times

extern "C" {
    unsigned golfed_adler32_amd64(int /*dummy1*/, const char *buf, int /*dummy2*/, unsigned len);
    unsigned adler32arm_golf(const char *buf, unsigned len);
}
#ifdef __amd64__
#define golfed_adler32(buf, len)   golfed_adler32_amd64(1234, buf, 1234, len)
#elif  __arm__
#define golfed_adler32(buf, len)   adler32arm_golf(buf, len)
#else
#error "no architecture"
#endif

static void test_adler(const char *str)
{
    unsigned len = strlen(str);
//    unsigned zlib = zlib_adler(len, str);
    unsigned reference = adler32_simple((const uint8_t*)str);
    unsigned golfed = golfed_adler32(str, len);

    printf("%s: c:%u asm:%u\n", str, reference, golfed);
    assert(reference == golfed);
}

// main() to call test_adler() unchanged from my amd64 answer, except that the comments about length limits don't apply


问:
Tips for golfing in Swift
What are some tips for code-golfing in Swift? Its focus on safety seems to make it difficult to golf in, but that makes little tips and even more useful. Are there any features in Swift that may help it excel in code-golf in certain applications?

Please post one tip per answer.

答:
Ranges

One thing that is really helpful is creating ranges using the ... or ..< operators

For example

array[0..<n] //first n elements of array
array[k..<n] //kth through nth elements of array
array[k...n] //kth through n-1 elements of array
```

<p>So, to get the 2nd through 4th values of an array</p>

<pre class="lang-swift prettyprint-override"><code>let myArray = ["ab", "cd", "ef", "gh", "ij", "kl", "mn", "op"]
print(myArray[1..<4]) //["cd", "ef", "gh"]
</code>```

Practical Use

let a = [3, 1, 4, 1, 5, 9]
```

<p>Using</p>

<pre class="lang-swift prettyprint-override"><code>for v in a[0...3]{print(v)}
</code>```

Is 8 bytes shorter than

for n in 0...3{let v=a[n];print(v)}
```

Title: Tips for golfing in Swift

Body:
Ranges

One thing that is really helpful is creating ranges using the ... or ..< operators

For example

array[0..<n] //first n elements of array
array[k..<n] //kth through nth elements of array
array[k...n] //kth through n-1 elements of array

So, to get the 2nd through 4th values of an array

let myArray = ["ab", "cd", "ef", "gh", "ij", "kl", "mn", "op"]
print(myArray[1..<4]) //["cd", "ef", "gh"]

Practical Use

let a = [3, 1, 4, 1, 5, 9]

Using

for v in a[0...3]{print(v)}

Is 8 bytes shorter than

for n in 0...3{let v=a[n];print(v)}


答:
Python, 379 bytes

```<code>from PIL.Image import*
from colorsys import*
def f(H,c,I):
 i=open(I);x,y=i.size;S=1.*c/(x*y);r,g,b=i.split();R=[];G=[];B=[]
 for x,y,z in zip(r.getdata(),g.getdata(),b.getdata()):
  e=255.;h,s,v=rgb_to_hsv(x/e,y/e,z/e);t=hsv_to_rgb(h+H,s,v);H=H+S%1.;x,y,z=[int(x*e)for x in t];R.append(x);G.append(y);B.append(z)
 p=Image.putdata;p(r,R);p(g,G);p(b,B);return merge('RGB',(r,g,b))
</code>```

This takes a path to a .jpg as input. It will not work with png, although you can change r,g,b=i.split(); to r,g,b=i.split()[:3]; to load a png image.

Here are some images:

Original:

Offset: 0, Cycles: 4

Original:

Offset 0, 1 cycle:

Original:

Offset 0, 2.5 cycles:

Title: Rainbowlify An Image

Body:
Python, 379 bytes

from PIL.Image import*
from colorsys import*
def f(H,c,I):
 i=open(I);x,y=i.size;S=1.*c/(x*y);r,g,b=i.split();R=[];G=[];B=[]
 for x,y,z in zip(r.getdata(),g.getdata(),b.getdata()):
  e=255.;h,s,v=rgb_to_hsv(x/e,y/e,z/e);t=hsv_to_rgb(h+H,s,v);H=H+S%1.;x,y,z=[int(x*e)for x in t];R.append(x);G.append(y);B.append(z)
 p=Image.putdata;p(r,R);p(g,G);p(b,B);return merge('RGB',(r,g,b))

This takes a path to a .jpg as input. It will not work with png, although you can change r,g,b=i.split(); to r,g,b=i.split()[:3]; to load a png image.

Here are some images:

Original:

Offset: 0, Cycles: 4

Original:

Offset 0, 1 cycle:

Original:

Offset 0, 2.5 cycles:


问:
Minimize Those Ones
Your task is to build a natural number using the fewest number of ones and only the operators + or -. For example, the number seven can be written 1+1+1+1+1+1+1=7, but it can also be written as 11-1-1-1-1=7. The first one uses 7 ones, while the latter only uses 6. Your task is to return the minimum number of ones that can be used given the input of some natural number, n.

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

Test cases

Input => Output

```<code>0 => 2 (since 1-1=0)
7 => 6
121 => 6
72 => 15
1000 => 7
2016 => 21
</code>```

答:
JavaScript (ES6), 92 bytes

f=(n,i=3)=>eval([...s=i.toString(3)].map(d=>"-+"[d]||"").join`1`+".0")-n?f(n,i+1):s.length-1```
<pre class="snippet-code-html lang-html prettyprint-override"><code>n = <input type="number" oninput="R.textContent=f(this.value)" /><pre id="R">``````
</div>
</div>
</p>

<h2>Explanation</h2>

<p>Recursive function. This generates all possible permutations of <code>1</code>s separated by either <code>+</code>, <code>-</code> or nothing. It does this by incrementing a base-3 number, turning it into an array of digits, converting each digit <code>0</code> to <code>-</code>, <code>1</code> to <code>+</code> and <code>2</code> to an empty string, then joining them together with <code>1</code>s. The resulting string is <code>eval</code>d as a JavaScript statement which returns the result of the equation.</p>

<p>Because the operators are joined with <code>1</code>s in between (like <code>+1+1+1+</code>), there are <code>length - 1</code> <code>1</code>s. The first operator is ignored (because <code>+1</code> = <code>1</code>, <code><nothing>1</code> = <code>1</code> and it's a number so there will never be a leading <code>0</code> for <code>-</code>) and the final operator is also ignored (by appending <code>.0</code> to the equation).</p>

<h3>Higher Output Version, 96 bytes</h3>

<p>The other version can't return outputs higher than ~10 because of the recursion call stack limit. This version uses a for loop instead of recursion, so it can return outputs up to ~33. The amount of time required increases exponentially though so I don't recommend testing it.</p>

<pre class="lang-js prettyprint-override"><code>n=>eval('for(a=3;eval([...s=a.toString(3)].map(d=>"-+"[d]||"").join`1`+".0")-n;)a++;s.length-1')
</code>```

Title: Minimize Those Ones

Body:
JavaScript (ES6), 92 bytes

f=(n,i=3)=>eval([...s=i.toString(3)].map(d=>"-+"[d]||"").join`1`+".0")-n?f(n,i+1):s.length-1

n = <input type="number" oninput="R.textContent=f(this.value)" /><pre id="R"></pre>

Explanation

Recursive function. This generates all possible permutations of 1s separated by either +, - or nothing. It does this by incrementing a base-3 number, turning it into an array of digits, converting each digit 0 to -, 1 to + and 2 to an empty string, then joining them together with 1s. The resulting string is evald as a JavaScript statement which returns the result of the equation.

Because the operators are joined with 1s in between (like +1+1+1+), there are length - 1 1s. The first operator is ignored (because +1 = 1, <nothing>1 = 1 and it's a number so there will never be a leading 0 for -) and the final operator is also ignored (by appending .0 to the equation).

Higher Output Version, 96 bytes

The other version can't return outputs higher than ~10 because of the recursion call stack limit. This version uses a for loop instead of recursion, so it can return outputs up to ~33. The amount of time required increases exponentially though so I don't recommend testing it.

n=>eval('for(a=3;eval([...s=a.toString(3)].map(d=>"-+"[d]||"").join`1`+".0")-n;)a++;s.length-1')


问:
Polygonal numbers
A polygonal number is the number of dots in a k-gon of size n.

You will be given n and k, and your task is to write a program/function that outputs/prints the corresponding number.

Scoring

This is code-golf. Shortest solution in bytes wins.

Example

The 3rd hexagon number (k=6, n=3) is 28 because there are 28 dots above.

Testcases

Can be generated from this Pyth test suite.

Usage: two lines per testcase, n above, k below.

```<code>n    k  output
10   3  55
10   5  145
100  3  5050
1000 24 10990000
</code>```

Further information

In Wikipedia: https://en.wikipedia.org/wiki/Polygonal_number

In Wolfram Mathworld: http://mathworld.wolfram.com/PolygonalNumber.html

In OEIS Wiki: http://oeis.org/wiki/Polygonal_numbers

OEIS sequences for n-gonal numbers for various n: 3 (A000217), 4 (A000290), 5 (A000326), 6 (A000384), 7 (A000566), 8 (A000567), 9 (A001106), 10 (A001107), 11 (A051682), 12 (A051624), 13 (A051865), 14 (A051866), 15 (A051867), 16 (A051868), 17 (A051869), 18 (A051870), 19 (A051871), 20 (A051872), 21 (A051873), 22 (A051874), 23 (A051875), 24 (A051876)

答:
Actually, 12 bytes

```<code>3@n(¬@D3╟π½+
</code>```

Try it online!

Explanation:

```<code>3@n(¬@D3╟π½+
3@n           push 3 copies of n (stack: [n, n, n, k])
   (¬         bring k to front and subtract 2 ([k-2, n, n, n])
     @D       bring an n to front and subtract 1 ([n-1, k-2, n, n])
       3╟π    product of top 3 elements ([n*(n-1)*(k-2), n])
          ½   divide by 2 ([n*(n-1)*(k-2)/2, n])
           +  add ([n*(n-1)*(k-2)/2 + n])
</code>```

Title: Polygonal numbers

Body:
Actually, 12 bytes

3@n(¬@D3╟π½+

Try it online!

Explanation:

3@n(¬@D3╟π½+
3@n           push 3 copies of n (stack: [n, n, n, k])
   (¬         bring k to front and subtract 2 ([k-2, n, n, n])
     @D       bring an n to front and subtract 1 ([n-1, k-2, n, n])
       3╟π    product of top 3 elements ([n*(n-1)*(k-2), n])
          ½   divide by 2 ([n*(n-1)*(k-2)/2, n])
           +  add ([n*(n-1)*(k-2)/2 + n])


问:
Reverse a 1-dimensional array
Note: This challenge is not the same.

Challenge

Believe it or not, we haven't got ONE challenge for reversing one-dimensional arrays (although we've got one for n-dimensional ones)! This should operate only on the 1st dimension, not on all dimensions of an array.

Rules

Standard loopholes are denied

[[1, 2], [3, 4]] becomes [[3, 4], [1, 2]], not [[4, 3], [2, 1]].

This is code-golf, but no answer is accepted. Go beat the others!

You can get the array any way, except hardcoding. You can also get a string and process it.

The input will be an array (yes, commas or no commas, it needs to be an array).

Test cases

These are the test cases:

```<code>[1, 2, 3, 4]
[1, 2, 'hello', 'world!']
[[1, 2, 3, 4], [2, 3, 4, 1]]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
</code>```

These are the supposed results:

```<code>[4, 3, 2, 1]
['world!', 'hello', 2, 1]
[[2, 3, 4, 1], [1, 2, 3, 4]]
[23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
</code>```

You may accept input as [1 2 3 4], or even 1 2 3 4, or any other form or array your language has.

答:
Brachylog, 2 bytes

```<code>r.
</code>```

which expects a list as Input and unifies the reverse with the Output.

Alternative

```<code>rw
</code>```

which expects a list as Input and writes the reverse to STDOUT.

Title: Reverse a 1-dimensional array

Body:
Brachylog, 2 bytes

r.

which expects a list as Input and unifies the reverse with the Output.

Alternative

rw

which expects a list as Input and writes the reverse to STDOUT.


问:
Invert png image
Create program or function that takes file name as an argument or reads it from standard input, and completes the following task:

Read image from a png file (name given as argument).

Reverse colors in that image, so that for example dark green (0, 75, 30) would become (255, 180, 225) (because 255-0=255, 255-75=180 and 255-30=225). You should not change alpha channel value.

Output that image to a file called a.png (in png format), or show it in GUI window.

This is code-golf. Standard loopholes apply.

答:
FFmpeg, 10 bytes

Edit: Taking a cue from @Sparr's answer

```<code>-vf negate
</code>```

(the above when passed to ffplay alongwith the image name, will display the negated image)

```<code>ffplay %1 -vf negate
</code>```

The above is saved as a batch file.

Title: Invert png image

Body:
FFmpeg, 10 bytes

Edit: Taking a cue from @Sparr's answer

-vf negate

(the above when passed to ffplay alongwith the image name, will display the negated image)

ffplay %1 -vf negate

The above is saved as a batch file.


问:
KOTH: Every coin has two sides
Final results available

Introduction

After my previous KOTH with heavy themes (fantasy war, worldwide pandemic...), I'm back with a new lighthearted game. This time, you are facing off in a "board game-like" situation. A pile of upside down coins is placed at the center of a really big table, and you are determined to get your share of the loot!

Glossary

Coins: Tokens that can either be flipped or unflipped.

  Unflipped: Coins placed on the table with their value pointing down. This is the default state of the coins.

  Flipped: Coins placed on the table with their value pointing up.

  Local: Refers to your pile of coins.

  Global: Refers to the pile of coins at the center.

Principle

At the start of the game, each player starts with 0 points and 0 coins (flipped or unflipped). The game is turn-based. During their turn, players can take up to 3 actions interacting either with the pile of coins at the center of the table, their own pile of coins or with other players.

Play order is defined randomly at the start of the game. The order of the players in the argument list represents the turn order, and it goes from left to right in that list. "Next" and "Previous" refer respectively to "on the right in that list" and "on the left in that list" with a loop if you're the last of either side.

The game lasts for 50 rounds or until there are 0 coins at the center at the end of a player turn (meaning that you will finish your 3 actions even if the pile is empty after your first action, and you can put back coins to let the game continue). The starting number of global coins is defined randomly with this formula:

```<code>(2 ^ nb_players) + (nb_players * 10) - random(1 + (nb_players ^ 2))`
</code>```

Each action will get you points (or make you lose some) and at the end of the game, each coin you have will be added to your points (-1 for unflipped, +2 for flipped). The player with the highest score wins.

The controller provides you with input via command arguments, and your program has to output via stdout.

Syntax

Input

Each time your program is called, it will receive arguments in this format:

Round;YourPlayerId;Coins;PlayerId_Points_Flipped_Unflipped;PlayerId_Points_Flipped_Unflipped;...

Rounds are 1-indexed.

Example input

6;2;52;1_20_3_12;0_-2_0_1;2_12_1_0

Here, you see it is the 6th round and you are player 2. There are 52 coins in the central pile. You have 12 points, 1 flipped coin and 0 unflipped coin. Points can be negative.

Output

You have to output three characters (no space, no separator), which each correspond to one action you'll take this turn. The order of the characters determine the order of the actions. You can output the same actions multiple times. In case there is not enough coins to complete your action, it will use the maximum of available coins and count points only for the coins used.

N: Do Nothing

1: Take 1 coin from the central pile [Effects: +1 local unflipped / -1 point / -1 global unflipped]

2: Take 2 coins from the central pile [Effects: +2 local unflipped / -2 points / -2 global unflipped]

3: Take 3 coins from the central pile [Effects: +3 local unflipped / -3 points / -3 global unflipped]

A: Put back 1 coin from your pile [Effects: -1 local unflipped / +1 point / +1 global unflipped]

B: Put back 2 coins from your pile [Effects: -2 local unflipped / +2 points / +2 global unflipped]

C: Put back 3 coins from your pile [Effects: -3 local unflipped / +3 points / +3 global unflipped]

X: Remove 1 coin from your pile [Effects: -1 local unflipped / 0 point]

Y: Remove 2 coins from your pile [Effects: -2 local unflipped / 0 point]

Z: Remove 3 coins from your pile [Effects: -3 local unflipped / 0 point]

R: Rotate coins to previous player [Effects: -1 point per unflipped received, +2 points per flipped received / applies to all players]

T: Rotate coins to next player [Effects: -1 point per unflipped received, +2 points per flipped received / applies to all players]

F: Flip 1 coin [Effects: -1 local unflipped / +1 local flipped / +2 point]

U: Unflip 1 coin [Effects: +1 local unflipped / -1 local flipped / -2 point]

Example output

2FF : Takes two coins and flips two coin, scoring -2 + 2 + 2 = 2 points

If your output is incorrect, controller will assume NNN.

Controller

You can find the controller on GitHub. It also contains two samplebots, written in Java.
To make it run, check out the project and open it in your Java IDE. The entry point in the main method of the class Game. Java 8 required.

To add bots, first you need either the compiled version for Java (.class files) or the sources for interpreted languages. Place them in the root folder of the project. Then, create a new Java class in the players package (you can take example on the already existing bots). This class must implement Player to override the method String getCmd(). The String returned is the shell command to run your bots. You can for example make a Ruby bot work with this command : return "C:\Ruby\bin\ruby.exe MyBot.rb";. Finally, add the bot in the players array at the top of the Game class.

Rules

Bots should not be written to beat or support specific other bots.

Writing to files is allowed. Please write to"yoursubmissionname.txt", the folder will be emptied before a game starts. Other external resources are disallowed.

Your submission has 1 second to respond.

Provide commands to compile and run your submissions.

Supported Languages

I'll try and support every language, but it needs to be available online for free. Please provide instructions for installation if you're not using a "mainstream" language.

As of right now, I can run : Java 6-7-8, PHP, Ruby, Perl, Python 2-3, Lua, R, node.js, Haskell, Kotlin, C++ 11.

Final results

These are the results of 100 games (points are added up) :

```<code>1. BirdInTheHand: 1017790
2. Balance: 851428
3. SecondBest: 802316
4. Crook: 739080
5. Jim: 723440
6. Flipper: 613290
7. Wheeler: 585516
8. Oracle: 574916
9. SimpleBot: 543665
10. TraderBot: 538160
11. EgoisticalBot: 529567
12. RememberMe: 497513
13. PassiveBot: 494441
14. TheJanitor: 474069
15. GreedyRotation: 447057
16. Devil: 79212
17. Saboteur: 62240
</code>```

Individual results of the games are available here : http://pasted.co/63f1e924 (with starting coins and number of rounds per game).

A bounty of 50 reputations is awarded to the winner : Bird In The Hand by Martin Büttner.

Thank you all for your participation, see you next KOTH~

答:
The Janitor, Python 3

He tries to clean the mess the other players make with all these coins and put them back into pool.

```<code>import sys;
def Parse(S):
    T = S.split(';');
    me = eval(T[1]);
    N = len(T)-3;
    A = list(map(lambda x: list(map(lambda y:int(y),T[3+((2*N+x+me)%N)].split('_'))),range(-3,4)));
    Dic = {}
    for a in A:
        Dic[a[0]] = a[1:];
    Dic[-1] = [me];
    return Dic;
def Recursive(Dic,me,D):
    if D==3: return '';
    V = Dic[me];
    N = max(Dic.keys());
    Next = (me+1)%N;
    Prev = (N+1+me)%N;
    for i in range(3,0,-1):
        if V[2]>=i:
            Dic[me][2] = Dic[me][2]-i;
            return chr((i-1)+ord('A'))+Recursive(Dic,me,D+1);
    if V[1]>0:
        Dic[me][1] = Dic[me][1]-1;
        Dic[me][2] = Dic[me][2]+1;
        return 'U'+Recursive(Dic,me,D+1);
    if Dic[Next][2]>Dic[Prev][2]:
        return 'T'+Recursive(Dic,Next,D+1);
    return 'R'+Recursive(Dic,Prev,D+1);
Dic = Parse(sys.argv[1]);
me = Dic[-1][0];
print(Recursive(Dic,me,0));
</code>```

He tries to give back all his unflipped coins, if he has some stuck flipped coins he will unflip them and if he gets rid of all his coins he will get somebody's else.

Title: KOTH: Every coin has two sides

Body:
The Janitor, Python 3

He tries to clean the mess the other players make with all these coins and put them back into pool.

import sys;
def Parse(S):
    T = S.split(';');
    me = eval(T[1]);
    N = len(T)-3;
    A = list(map(lambda x: list(map(lambda y:int(y),T[3+((2*N+x+me)%N)].split('_'))),range(-3,4)));
    Dic = {}
    for a in A:
        Dic[a[0]] = a[1:];
    Dic[-1] = [me];
    return Dic;
def Recursive(Dic,me,D):
    if D==3: return '';
    V = Dic[me];
    N = max(Dic.keys());
    Next = (me+1)%N;
    Prev = (N+1+me)%N;
    for i in range(3,0,-1):
        if V[2]>=i:
            Dic[me][2] = Dic[me][2]-i;
            return chr((i-1)+ord('A'))+Recursive(Dic,me,D+1);
    if V[1]>0:
        Dic[me][1] = Dic[me][1]-1;
        Dic[me][2] = Dic[me][2]+1;
        return 'U'+Recursive(Dic,me,D+1);
    if Dic[Next][2]>Dic[Prev][2]:
        return 'T'+Recursive(Dic,Next,D+1);
    return 'R'+Recursive(Dic,Prev,D+1);
Dic = Parse(sys.argv[1]);
me = Dic[-1][0];
print(Recursive(Dic,me,0));

He tries to give back all his unflipped coins, if he has some stuck flipped coins he will unflip them and if he gets rid of all his coins he will get somebody's else.


问:
Automatic house-builder
Automatic house building nanobots have been fabricated, and it's your job to code them.

Here is the house created by input 7 4 2

```<code>  /-----/|
 /     / |
|-----|  |
|     |  |
|     | /
|_____|/
</code>```

The input is a string containing the house's dimensions.

7 is the width.

```<code>|_____|

---7---
</code>```

4 is the height.

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

2 is the depth

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

Given this input, can you create the house?

Your code must be as small as possible so that it can fit in the robots.

Notes

The smallest dimensions you will be given as input are 3 2 2. Your program can do anything with dimensions that are smaller than 3 2 2.

Testcases

```<code>3 2 10

          /-/|
         / / |
        / / /
       / / /
      / / /
     / / /
    / / /
   / / /
  / / /
 / / /
|-| /
|_|/
</code>```

答:
Python 2, 128 bytes

w,h,d=input();i=d
while-i<h:c='|/'[i>0];print' '*i+c+'- _'[(d>i!=0)+(h+i<2)]*(w-2)+c+' '*min(d-i,h-1,w+1,h-1+i)+'/|'[d-i<h];i-=1
```

Prints row by row. The row indices i count down from d to -h+1.

Title: Automatic house-builder

Body:
Python 2, 128 bytes

w,h,d=input();i=d
while-i<h:c='|/'[i>0];print' '*i+c+'- _'[(d>i!=0)+(h+i<2)]*(w-2)+c+' '*min(d-i,h-1,w+1,h-1+i)+'/|'[d-i<h];i-=1

Prints row by row. The row indices i count down from d to -h+1.


答:
Python + PIL, 85 bytes

from PIL import Image
lambda a:Image.eval(Image.open(a),lambda x:255-x).save('a.png')
```

This defines an anonymous function that takes a filename as a string and saves the resultant image to a.png.

Test run:

Title: Invert png image

Body:
Create program or function that takes file name as an argument or reads it from standard input, and completes the following task:

Read image from a png file (name given as argument).

Reverse colors in that image, so that for example dark green (0, 75, 30) would become (255, 180, 225) (because 255-0=255, 255-75=180 and 255-30=225). You should not change alpha channel value.

Output that image to a file called a.png (in png format), or show it in GUI window.

This is code-golf. Standard loopholes apply.

Body:
Python + PIL, 85 bytes

from PIL import Image
lambda a:Image.eval(Image.open(a),lambda x:255-x).save('a.png')

This defines an anonymous function that takes a filename as a string and saves the resultant image to a.png.

Test run:


问:
Reconstruct a missing RGB channel
Look at these photographs of natural scenes, with one of the RGB channels taken out of them:

Source (with red): https://en.wikipedia.org/wiki/File:Altja_j%C3%B5gi_Lahemaal.jpg

Source (with green): https://commons.wikimedia.org/wiki/File:2007_mather-lake_hg.jpg

Source (with blue): https://commons.wikimedia.org/wiki/File:Fox_01.jpg

Even without one of the channels, you can probably make out what colours certain things are supposed to be, or at least have a good idea if a reconstruction of the missing channel is accurate.

For example, here is the first picture with a red channel added back onto it which is just random noise:

This image clearly isn't an accurate reconstruction of the red channel. This is because nature photos generally don't use the entire RGB spectrum, but only a subset of "natural-looking colours". Also, the shades of red will follow certain gradients that correlate with the others.

Your task is to build a program that will take a photograph that's had one channel removed and attempt to approximate the original image as closely as possible by reconstructing what it believes is the missing channel.

Your program will be scored on how closely the missing channel matches with the channel of the original image, by counting the percentage of pixels whose values of that channel are within ±15 (inclusive) of the actual value in the original image (where the values range from 0 to 255 as in a standard 8-bit colour channel).

The test cases that your program will be scored on can be found here (9.04 MB zip file, 6 images). Currently it only contains the three example images above and their originals, but I'll add a few more later to make the full suite once I've done them.

Each image is scaled down and cropped to 1024 x 768, so they will have the same weight in your score. The program that can predict the most pixels within the given tolerance wins.

答:
Python 3 + scikit-image

Simply sets the color of the missing channel to the average of the other two.

```<code>import sys
from skimage import io, color

im = io.imread(sys.argv[1])
h, w, c = im.shape

removed_channel_options = {0, 1, 2}
for y in range(h):
    for x in range(w):
        if len(removed_channel_options) == 1: break
        removed_channel_options -= {i for i, c in enumerate(im[y][x]) if c > 0}
removed_channel = removed_channel_options.pop()

for y in range(h):
    for x in range(w):
        p = [float(c) / 255 for c in im[y][x][:3]]
        p = [sum(p)/2 if i == removed_channel else p[i]
             for i in range(3)]
        im[y][x] = [int(c*255) for c in p] + [255]*(c == 4)

io.imsave(sys.argv[2], im)
</code>```

And the restored images:

Title: Reconstruct a missing RGB channel

Body:
Python 3 + scikit-image

Simply sets the color of the missing channel to the average of the other two.

import sys
from skimage import io, color

im = io.imread(sys.argv[1])
h, w, c = im.shape

removed_channel_options = {0, 1, 2}
for y in range(h):
    for x in range(w):
        if len(removed_channel_options) == 1: break
        removed_channel_options -= {i for i, c in enumerate(im[y][x]) if c > 0}
removed_channel = removed_channel_options.pop()

for y in range(h):
    for x in range(w):
        p = [float(c) / 255 for c in im[y][x][:3]]
        p = [sum(p)/2 if i == removed_channel else p[i]
             for i in range(3)]
        im[y][x] = [int(c*255) for c in p] + [255]*(c == 4)

io.imsave(sys.argv[2], im)

And the restored images:

ContentLicense: CC BY-SA 4.0


答:
JavaScript (ES6), <s>127</s> <s>126</s> 87 bytes

f=(n,z=2,m=n*9+'',r=m.replace(/./g,1))=>n?m.length+(m<'55'?f(n- --r/10,0)-1:f(r-n,0)):z```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Input: <input type="number" oninput="result.textContent=f(this.value)"> Result: <span id="result"></span></code>```

Should work to about 10<s>14</s>15 at which point you start running into JavaScript's integer limits. Explanation:

```<code>f=(                             Recursive function
 n,                             Parameter
 z=2,                           Zero workaround
 m=n*9+'',                      Magic
 r=m.replace(/./g,1)            Find repunit not less than than n
)=>n?                           Nothing to do if n is zero
 m.length+                      Assume subtracting from repunit
 (m<'55'?                       Should we subtract from repunit?
  f(n- --r/10,0)                No, so subtract previous repuint
   -1:                          Which is one 1 shorter
  f(r-n,0)):                    Subtract from repunit
 z                              Return special case if n is zero
</code>```

This uses the n*9 magic twice; firstly, it gives me the length of the next repunit, secondly, if the first two digits of n*9 are 55 or higher, then we need to subtract n from that next repunit, otherwise we need to subtract the previous repunit (which is calculated by subtracting 1 and dividing by 10). This should work up to 1015.

Title: Minimize Those Ones

Body:
Your task is to build a natural number using the fewest number of ones and only the operators + or -. For example, the number seven can be written 1+1+1+1+1+1+1=7, but it can also be written as 11-1-1-1-1=7. The first one uses 7 ones, while the latter only uses 6. Your task is to return the minimum number of ones that can be used given the input of some natural number, n.

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

Test cases

Input => Output

```<code>0 => 2 (since 1-1=0)
7 => 6
121 => 6
72 => 15
1000 => 7
2016 => 21
</code>```

Body:
JavaScript (ES6), <s>127</s> <s>126</s> 87 bytes

f=(n,z=2,m=n*9+'',r=m.replace(/./g,1))=>n?m.length+(m<'55'?f(n- --r/10,0)-1:f(r-n,0)):z

Input: <input type="number" oninput="result.textContent=f(this.value)"> Result: <span id="result"></span>

Should work to about 10<s>14</s>15 at which point you start running into JavaScript's integer limits. Explanation:

f=(                             Recursive function
 n,                             Parameter
 z=2,                           Zero workaround
 m=n*9+'',                      Magic
 r=m.replace(/./g,1)            Find repunit not less than than n
)=>n?                           Nothing to do if n is zero
 m.length+                      Assume subtracting from repunit
 (m<'55'?                       Should we subtract from repunit?
  f(n- --r/10,0)                No, so subtract previous repuint
   -1:                          Which is one 1 shorter
  f(r-n,0)):                    Subtract from repunit
 z                              Return special case if n is zero

This uses the n*9 magic twice; firstly, it gives me the length of the next repunit, secondly, if the first two digits of n*9 are 55 or higher, then we need to subtract n from that next repunit, otherwise we need to subtract the previous repunit (which is calculated by subtracting 1 and dividing by 10). This should work up to 1015.


问:
Probability of something happening at least n out of m times
Write a program or function, that given a success probability p, a number n and a number of trials m returns the chance of at least n successes out of m trials.

Your answer must be precise to at least 5 digits after the decimal.

Test cases:

```<code> 0.1, 10, 100 -> 0.54871
 0.2, 10, 100 -> 0.99767
 0.5, 13,  20 -> 0.13159
 0.5,  4,   4 -> 0.06250
0.45, 50, 100 -> 0.18273
 0.4, 50, 100 -> 0.02710
   1,  1,   2 -> 1.00000
   1,  2,   1 -> 0.00000
   0,  0,   1 -> 1.00000
   0,  0,   0 -> 1.00000
   0,  1,   1 -> 0.00000
   1,  1,   0 -> 0.00000
</code>```

答:
Python, 57 bytes

f=lambda p,n,m:m and(1-p)*f(p,n,m-1)+p*f(p,n-1,m-1)or n<1
```

The recursive formula for binomial coefficients, except the base case m==0 indicates whether the remaining number of required successes n is nonnegative, with True/False for 1/0. Because of its exponential recursion tree, this stalls on large inputs.

Body:
Python, 57 bytes

f=lambda p,n,m:m and(1-p)*f(p,n,m-1)+p*f(p,n-1,m-1)or n<1

The recursive formula for binomial coefficients, except the base case m==0 indicates whether the remaining number of required successes n is nonnegative, with True/False for 1/0. Because of its exponential recursion tree, this stalls on large inputs.


答:
Pyth, 26 bytes

```<code>AQJEsm**.cHd^Jd^-1J-HdrGhH
</code>```

Try it online!

Uses standard cumulative binomial distribution.

Title: Probability of something happening at least n out of m times

Body:
Write a program or function, that given a success probability p, a number n and a number of trials m returns the chance of at least n successes out of m trials.

Your answer must be precise to at least 5 digits after the decimal.

Test cases:

```<code> 0.1, 10, 100 -> 0.54871
 0.2, 10, 100 -> 0.99767
 0.5, 13,  20 -> 0.13159
 0.5,  4,   4 -> 0.06250
0.45, 50, 100 -> 0.18273
 0.4, 50, 100 -> 0.02710
   1,  1,   2 -> 1.00000
   1,  2,   1 -> 0.00000
   0,  0,   1 -> 1.00000
   0,  0,   0 -> 1.00000
   0,  1,   1 -> 0.00000
   1,  1,   0 -> 0.00000
</code>```

Body:
Pyth, 26 bytes

AQJEsm**.cHd^Jd^-1J-HdrGhH

Try it online!

Uses standard cumulative binomial distribution.


答:
Mathematica, 29 bytes

```<code>BetaRegularized[#3,#,1+#2-#]&
</code>```

Takes input in the order n,m,p. Mathematica is so good, it even golfs your code for you:

BetaRegularized is the regularised incomplete beta function.

Body:
Mathematica, 29 bytes

BetaRegularized[#3,#,1+#2-#]&

Takes input in the order n,m,p. Mathematica is so good, it even golfs your code for you:

BetaRegularized is the regularised incomplete beta function.


答:
Pyth, 20 bytes

```<code>JEKEcsmgsm<O0QKJCGCG
</code>```

Try it online!

Note: CG is a very large number which the interpreter cannot handle. Therefore, the number of trials have been lowered to ^T3 which is one thousand. Therefore, the link produces an inaccurate result.

Uses pure probabilistic approach.

Body:
Pyth, 20 bytes

JEKEcsmgsm<O0QKJCGCG

Try it online!

Note: CG is a very large number which the interpreter cannot handle. Therefore, the number of trials have been lowered to ^T3 which is one thousand. Therefore, the link produces an inaccurate result.

Uses pure probabilistic approach.


问:
Golf Text into DNA

Text to DNA golf

Challenge

Convert input into a DNA output.

Algorithm

Convert text into ASCII code points (e.g. codegolf -> [99, 111, 100, 101, 103, 111, 108, 102])

String the ASCII codes together (e.g. 99111100101103111108102)

Convert to binary (e.g. 10100111111001101001011010001000011001101011011110000110010111111011000000110)

Pad 0s onto the end to make an even number of characters (e.g. 101001111110011010010110100010000110011010110111100001100101111110110000001100)

Replace 00 with A, 01 with C, 10 with G, and 11 with T (e.g. GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA)

Output

Test Cases

```<code>codegolf > GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA
ppcg > GGCTAATTGTCGCACTT
} > TTGG (padding)
</code>```

Specifications

This is code-golf

Your program must accept spaces in input.

Your program must work for codegolf.

答:
Ruby, 59 bytes

```<code>$_='%b0'.%$_.bytes*''
gsub(/../){:ACGT[$&.hex%7]}
chomp'0'
</code>```

A full program. Run with the -p flag.

Title: Golf Text into DNA

Body:
Ruby, 59 bytes

$_='%b0'.%$_.bytes*''
gsub(/../){:ACGT[$&.hex%7]}
chomp'0'

A full program. Run with the -p flag.


答:
Haskell, 73 bytes

g x=product[1..x];f p n m=sum[g m/g k/g(m-k)*p**k*(1-p)**(m-k)|k<-[n..m]]
```


答:
R, <s>32</s> 31 bytes

```<code>function(p,n,m)pbeta(p,m,1+n-m)
</code>```

edit - 1 byte switching to beta distribution (along the lines of @Sp3000 Mathematica Answer)

Body:
R, <s>32</s> 31 bytes

function(p,n,m)pbeta(p,m,1+n-m)

edit - 1 byte switching to beta distribution (along the lines of @Sp3000 Mathematica Answer)


答:
MATLAB, <s>78</s> 71 bytes

Saved 7 bytes thanks to Luis Mendo!

```<code>@(m,k,p)sum(arrayfun(@(t)prod((1:m)./[1:t 1:m-t])*p^t*(1-p)^(m-t),k:m))

ans(100,10,0.1)
0.5487
</code>```

The arrayfun function is no fun, but I haven't found a way to get rid of it...

Body:
MATLAB, <s>78</s> 71 bytes

Saved 7 bytes thanks to Luis Mendo!

@(m,k,p)sum(arrayfun(@(t)prod((1:m)./[1:t 1:m-t])*p^t*(1-p)^(m-t),k:m))

ans(100,10,0.1)
0.5487

The arrayfun function is no fun, but I haven't found a way to get rid of it...


答:
JavaScript (ES7), 82 bytes

```<code>(p,n,m)=>[...Array(++m)].reduce((r,_,i)=>r+(b=!i||b*m/i)*p**i*(1-p)**--m*(i>=n),0)
</code>```

Saved 1 byte by using reduce! Explanation:

```<code>(p,n,m)=>               Parameters
 [...Array(++m)].       m+1 terms
  reduce((r,_,i)=>r+    Sum
   (b=!i||b*m/i)*       Binomial coefficient
   p**i*(1-p)**--m*     Probability
   (i>=n),              Ignore first n terms
   0)
</code>```

Body:
JavaScript (ES7), 82 bytes

(p,n,m)=>[...Array(++m)].reduce((r,_,i)=>r+(b=!i||b*m/i)*p**i*(1-p)**--m*(i>=n),0)

Saved 1 byte by using reduce! Explanation:

(p,n,m)=>               Parameters
 [...Array(++m)].       m+1 terms
  reduce((r,_,i)=>r+    Sum
   (b=!i||b*m/i)*       Binomial coefficient
   p**i*(1-p)**--m*     Probability
   (i>=n),              Ignore first n terms
   0)


答:
MATL, 23 bytes

```<code>y2$:Xni5M^1IG-lG7M-^**s
</code>```

Inputs are in the order m, n, p.

Try it online!

This does a direct computation summing the terms from n to m of the binomial probability (mass) function.

Body:
MATL, 23 bytes

y2$:Xni5M^1IG-lG7M-^**s

Inputs are in the order m, n, p.

Try it online!

This does a direct computation summing the terms from n to m of the binomial probability (mass) function.


答:
Octave, 26 bytes

```<code>@(p,n,m)1-binocdf(n-1,m,p)
</code>```

This is an anonymous function. To use it, assign it to a variable.

Try it here.

Body:
Octave, 26 bytes

@(p,n,m)1-binocdf(n-1,m,p)

This is an anonymous function. To use it, assign it to a variable.

Try it here.


答:
Lua, 61 bytes

It beats C! \o/

It simply fill a new table in the reversed order.

function f(g)h={}for i=0,#g do h[#g-i]=g[i+1]end return h end
```
<p>It could have been done by working on the pointer, suppressing the return statement and the new table definition, but it actually is longer by 2 bytes</p>
<pre class="lang-lua prettyprint-override"><code>function f(g)for i=1,#g/2 do x=#g-i+1g[x],g[i]=g[i],g[x]end end
</code>```

Title: Reverse a 1-dimensional array

Body:
Note: This challenge is not the same.

Challenge

Believe it or not, we haven't got ONE challenge for reversing one-dimensional arrays (although we've got one for n-dimensional ones)! This should operate only on the 1st dimension, not on all dimensions of an array.

Rules

Standard loopholes are denied

[[1, 2], [3, 4]] becomes [[3, 4], [1, 2]], not [[4, 3], [2, 1]].

This is code-golf, but no answer is accepted. Go beat the others!

You can get the array any way, except hardcoding. You can also get a string and process it.

The input will be an array (yes, commas or no commas, it needs to be an array).

Test cases

These are the test cases:

```<code>[1, 2, 3, 4]
[1, 2, 'hello', 'world!']
[[1, 2, 3, 4], [2, 3, 4, 1]]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
</code>```

These are the supposed results:

```<code>[4, 3, 2, 1]
['world!', 'hello', 2, 1]
[[2, 3, 4, 1], [1, 2, 3, 4]]
[23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
</code>```

You may accept input as [1 2 3 4], or even 1 2 3 4, or any other form or array your language has.

Body:
Lua, 61 bytes

It beats C! \o/

It simply fill a new table in the reversed order.

function f(g)h={}for i=0,#g do h[#g-i]=g[i+1]end return h end

It could have been done by working on the pointer, suppressing the return statement and the new table definition, but it actually is longer by 2 bytes

function f(g)for i=1,#g/2 do x=#g-i+1g[x],g[i]=g[i],g[x]end end


答:
Pyth, 23 bytes

```<code>sm@"AGCT"i_d2c.BsjkCMQ2
</code>```

Try it online!

Explanation

Borrowing the trick from Dennis' Jelly answer.

```<code>sm@"AGCT"i_d2c.BsjkCMQ2
                   CMQ   convert each character to its byte value
                sjk      convert to a string and then to integer
              .B         convert to binary
             c        2  chop into pairs
 m         d             for each pair:
          _                  reverse it
         i  2                convert from binary to integer
  @"AGCT"                    find its position in "AGCT"
s                        join the string
</code>```

Title: Golf Text into DNA

Body:
Text to DNA golf

Challenge

Convert input into a DNA output.

Algorithm

Convert text into ASCII code points (e.g. codegolf -> [99, 111, 100, 101, 103, 111, 108, 102])

String the ASCII codes together (e.g. 99111100101103111108102)

Convert to binary (e.g. 10100111111001101001011010001000011001101011011110000110010111111011000000110)

Pad 0s onto the end to make an even number of characters (e.g. 101001111110011010010110100010000110011010110111100001100101111110110000001100)

Replace 00 with A, 01 with C, 10 with G, and 11 with T (e.g. GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA)

Output

Test Cases

```<code>codegolf > GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA
ppcg > GGCTAATTGTCGCACTT
} > TTGG (padding)
</code>```

Specifications

This is code-golf

Your program must accept spaces in input.

Your program must work for codegolf.

Body:
Pyth, 23 bytes

sm@"AGCT"i_d2c.BsjkCMQ2

Try it online!

Explanation

Borrowing the trick from Dennis' Jelly answer.

sm@"AGCT"i_d2c.BsjkCMQ2
                   CMQ   convert each character to its byte value
                sjk      convert to a string and then to integer
              .B         convert to binary
             c        2  chop into pairs
 m         d             for each pair:
          _                  reverse it
         i  2                convert from binary to integer
  @"AGCT"                    find its position in "AGCT"
s                        join the string


答:
TI-Basic, 17 bytes

Precise to 10 decimals, could be adjusted anywhere from 0-14 decimals with more code.

```<code>Prompt P,N,M:1-binomcdf(M,P,N-1
</code>```

Body:
TI-Basic, 17 bytes

Precise to 10 decimals, could be adjusted anywhere from 0-14 decimals with more code.

Prompt P,N,M:1-binomcdf(M,P,N-1


问:
The rice and chess problem
An Indian legend tells the story of the alleged inventor of the chess game, who impressed the emperor of India with his game so much that he would get rewarded with anything asked.

The man said he wanted to be paid in rice. He wanted a grain of rice for the first square of the chessboard, two for the second, four for the third, eight for the fourth, and so on, until the 64th square.

The emperor was amazed that the man asked for such a small reward, but as his mathematicians started counting, he ended up losing one of his provinces.

Task

Given the length of the side of a hypothetical chessboard (which is 8 on a default chessboard) and the multiplier between squares (which is 2 in the legend), calculate the number of grains of rice the emperor must pay to the man.

Notes

The side length will always be a positive integer. The multiplier could instead be any kind of rational number.

If your language of choice can't display very large numbers, it's okay as long as your program can correctly process smaller inputs.

Also if your language of choice rounds larger values (with exponential notations), it's okay if those values are approximately correct.

Testcases

```<code>Input (side length, multiplier) => Output
8, 2                            => 18446744073709551615
3, 6                            => 2015539
7, 1.5                          => 850161998.2854
5, -3                           => 211822152361
256, 1                          => 65536
2, 2                            => 15
2, -2                           => -5
</code>```

Please note that the explicit formula

```<code>result = (multiplier ^ (side ^ 2) - 1) / (multiplier - 1)
</code>```

Performs wrong on multiplier = 1, as

```<code>1 ^ (side ^ 2) - 1 = 0
1 - 1 = 0
0 / 0 != side ^ 2 (as it should be)
</code>```

Scoring

This is code-golf. Shortest answer in bytes wins.

答:
Pyth, 6 bytes

1 byte saved thanks to @FryAmTheEggman.

```<code>s^Lvz*
</code>```

Try it online!

Test suite.

Title: The rice and chess problem

Body:
Pyth, 6 bytes

1 byte saved thanks to @FryAmTheEggman.

s^Lvz*

Try it online!

Test suite.


答:
Jelly, 6 bytes

```<code>²R’*@S
</code>```

Try it online!

Title: The rice and chess problem

Body:
An Indian legend tells the story of the alleged inventor of the chess game, who impressed the emperor of India with his game so much that he would get rewarded with anything asked.

The man said he wanted to be paid in rice. He wanted a grain of rice for the first square of the chessboard, two for the second, four for the third, eight for the fourth, and so on, until the 64th square.

The emperor was amazed that the man asked for such a small reward, but as his mathematicians started counting, he ended up losing one of his provinces.

Task

Given the length of the side of a hypothetical chessboard (which is 8 on a default chessboard) and the multiplier between squares (which is 2 in the legend), calculate the number of grains of rice the emperor must pay to the man.

Notes

The side length will always be a positive integer. The multiplier could instead be any kind of rational number.

If your language of choice can't display very large numbers, it's okay as long as your program can correctly process smaller inputs.

Also if your language of choice rounds larger values (with exponential notations), it's okay if those values are approximately correct.

Testcases

```<code>Input (side length, multiplier) => Output
8, 2                            => 18446744073709551615
3, 6                            => 2015539
7, 1.5                          => 850161998.2854
5, -3                           => 211822152361
256, 1                          => 65536
2, 2                            => 15
2, -2                           => -5
</code>```

Please note that the explicit formula

```<code>result = (multiplier ^ (side ^ 2) - 1) / (multiplier - 1)
</code>```

Performs wrong on multiplier = 1, as

```<code>1 ^ (side ^ 2) - 1 = 0
1 - 1 = 0
0 / 0 != side ^ 2 (as it should be)
</code>```

Scoring

This is code-golf. Shortest answer in bytes wins.

Body:
Jelly, 6 bytes

²R’*@S

Try it online!


答:
MATL, 6 bytes

```<code>2^:q^s
</code>```

Try it online!

```<code>2^   % Take implicit input, say N, and square it: N^2
:q   % Generate array [0 1 ... N^2-1]
^    % Take implicit input, M, and compute [M^0 M^1 ... M^(N^2-1)]
s    % Sum of the array. Implicit display
</code>```

Title: The rice and chess problem

Body:
MATL, 6 bytes

2^:q^s

Try it online!

2^   % Take implicit input, say N, and square it: N^2
:q   % Generate array [0 1 ... N^2-1]
^    % Take implicit input, M, and compute [M^0 M^1 ... M^(N^2-1)]
s    % Sum of the array. Implicit display


答:
Python, 40 bytes

```<code>lambda l,m:sum(m**i for i in range(l*l))
</code>```

Title: The rice and chess problem

Body:
Python, 40 bytes

lambda l,m:sum(m**i for i in range(l*l))


答:
TI-Basic, 19 bytes

S is side length, and M is the multiplier.

```<code>Prompt S,M:Σ(M^I,I,0,S²-1
</code>```

Title: The rice and chess problem

Body:
TI-Basic, 19 bytes

S is side length, and M is the multiplier.

Prompt S,M:Σ(M^I,I,0,S²-1


答:
Javascript ES6, <s>59</s> <s>37</s> <s>35</s> 34 bytes

```<code>a=>b=>(Math.pow(b,a*a)-1)/--b||a*a`
</code>```

Thanks to @Kaizo for shaving off a whopping 19 bytes, @Neil for another 2 and @gcampbell for 1 more!

Try it here

f=
a=>b=>(Math.pow(b,a*a)-1)/--b||a*a

a.innerHTML='```'+
  [[8,2],
   [3,6],
   [7,1.5],
   [5,-3],
   [256,1],
   [2,2],
   [2,-2]].map(b=>`${b[0]}, ${b[1]} => ${f(b[0])(b[1])}`).join('<br>')+'```'```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id=a></code>```

Alternative broken versions

32 bytes

```<code>(a,b)=>(Math.pow(b,a*a)-1)/(b-1)
</code>```

Causes NaN for b==1.

30 bytes

```<code>(a,b)=>(Math.pow(b,a*a)-1)/~-b
</code>```

Causes Infinity for b==1.5.

28 bytes

```<code>(a,b)=>~-Math.pow(b,a*a)/~-b
</code>```

Outputs 1 for some valid testcases.

Old version for 59 bytes

(a,b)=>Array(a*a).fill``.reduce((c,d,i)=>c+Math.pow(b,i),0)

Title: The rice and chess problem

Body:
Javascript ES6, <s>59</s> <s>37</s> <s>35</s> 34 bytes

a=>b=>(Math.pow(b,a*a)-1)/--b||a*a`

Thanks to @Kaizo for shaving off a whopping 19 bytes, @Neil for another 2 and @gcampbell for 1 more!

Try it here

f=
a=>b=>(Math.pow(b,a*a)-1)/--b||a*a

a.innerHTML='<pre>'+
  [[8,2],
   [3,6],
   [7,1.5],
   [5,-3],
   [256,1],
   [2,2],
   [2,-2]].map(b=>`${b[0]}, ${b[1]} => ${f(b[0])(b[1])}`).join('<br>')+'</pre>'

<div id=a>

Alternative broken versions

32 bytes

(a,b)=>(Math.pow(b,a*a)-1)/(b-1)

Causes NaN for b==1.

30 bytes

(a,b)=>(Math.pow(b,a*a)-1)/~-b

Causes Infinity for b==1.5.

28 bytes

(a,b)=>~-Math.pow(b,a*a)/~-b

Outputs 1 for some valid testcases.

Old version for 59 bytes

(a,b)=>Array(a*a).fill``.reduce((c,d,i)=>c+Math.pow(b,i),0)


问:
Print the Nth non-palindromic number
A palindromic number (in case you don't know) is a number which reads the same backwards and forwards (example, 11). The first 15 non-palindromic numbers are: 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26. This is A029742. I constantly need these numbers, but my sticky note pad is very small, so your code must be as short as possible.

Rules

Each submission must be a full program or function (e.g. in C, you can't just define a function without headers, but you can define a function WITH necessary headers
).

If it is possible, provide a link to a site where your program can be tested.

Your program must not write anything to STDERR.

You can take input as an argument or from STDIN (or the closest alternative in your language).

Programs are scored according to bytes. The usual character set is UTF-8, if you are using another please specify.

Standard loopholes are forbidden.

Test Cases

```<code>1
==> 10

-----

5
==> 15

-----

12
==> 23
</code>```

Scoring

This is code-golf, so least bytes wins.

Submissions

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 leaderboard snippet:

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

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 79251; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Pyth, 7 bytes

```<code>e.f!_I`
</code>```

Test suite

Explanation:

```<code>e.f!_I`
e.f!_I`ZQ    Implicit variable introduction.
 .f     Q    Find the first Q numbers whether the following is truthy,
             starting at 1, where Q is the input.
      `Z     Convert the number to a string.
     _I      Check if it's the same when reversed.
    !        Logical not.
 e           Return the last element of the list.
</code>```

Title: Print the Nth non-palindromic number

Body:
Pyth, 7 bytes

e.f!_I`

Test suite

Explanation:

e.f!_I`
e.f!_I`ZQ    Implicit variable introduction.
 .f     Q    Find the first Q numbers whether the following is truthy,
             starting at 1, where Q is the input.
      `Z     Convert the number to a string.
     _I      Check if it's the same when reversed.
    !        Logical not.
 e           Return the last element of the list.