问:
Smallest Bytecode Interpreter/VM
Leaderboard - JIT Compiled (Lower is better)

es1024 - 81.2 points (including a working compiler!)

Kieth Randall - 116 points

Ell - 121 points

Leaderboard - Interpreted (Lower is better)

Martin Büttner - 706654 points (somewhere around 2 hours).

criptych - 30379 points (97 seconds)

Your mission, should you choose to accept it, is to write the smallest possible bytecode interpreter/VM. The VM/interpreter uses a small CISC architecture (operations can vary in size), with the language specified below. Upon completion, you must print the value of the 3 CPU registers to prove that the correct output is printed (3,126,900,366).

Compiler

If you'd like to make your own tests, a compiler is posted below. Feel free to post your tests with your answer.

window.compile=function(){var e=$("#text").val().toLowerCase().match(/[^\r\n]+/g);var t=[];for(var n=0;n<e.length;n++)compileLine(e[n],t);var r="";for(var n=0;n<t.length;n++)if(typeof t[n]=="string")r+="\n";else r+="0x"+t[n].toString(16)+" ";$("#compiledArray").val(r)};window.compileLine=function(e,t){var n=e.split(" ");if(n[0]=="load"){t.push(0);t.push(getInt(n[1]));t.pushArr(getInt(n[2]))}if(n[0]=="rload"){t.push(1);t.push(getInt(n[1]));t.push(getInt(n[1]))}if(n[0]=="push"){t.push(2);t.push(getInt(n[1]))}if(n[0]=="pop"){t.push(3);t.push(getInt(n[1]))}if(n[0]=="add"){t.push(4);t.push(getInt(n[1]));t.push(getInt(n[2]))}if(n[0]=="sub"){t.push(5);t.push(getInt(n[1]));t.push(getInt(n[2]))}if(n[0]=="mul"){t.push(6);t.push(getInt(n[1]));t.push(getInt(n[2]))}if(n[0]=="div"){t.push(7);t.push(getInt(n[1]));t.push(getInt(n[2]))}if(n[0]=="jmp"){t.push(8);t.pushArr(getInt(n[1]))}if(n[0]=="cmp"){t.push(9);t.push(getInt(n[1]));t.push(getInt(n[2]))}if(n[0]=="branchlt"){t.push(10);t.pushArr(getInt(n[1]))}if(n[0]=="brancheq"){t.push(11);t.pushArr(getInt(n[1]))}if(n[0]=="branchgt"){t.push(12);t.pushArr(getInt(n[1]))}if(n[0]=="branchne"){t.push(13);t.pushArr(getInt(n[1]))}t.push("NEW LINE")};window.getInt=function(e){if(e.trim().startsWith("<--"))return"COMMENT";if(e=="r0")return 0;if(e=="r1")return 1;if(e=="r2")return 2;if(e.startsWith("0x"))return parseInt(e,16);if(isNaN(parseInt(e)))alert(e);return getIntBytes(parseInt(e))};if(typeof String.prototype.startsWith!="function"){String.prototype.startsWith=function(e){return this.slice(0,e.length)==e}}Array.prototype.pushArr=function(e){this.push.apply(this,e)};window.getIntBytes=function(e){var t=[];var n=4;do{t[--n]=e&255;e=e>>8}while(n);return t}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea id="text" cols="40" rows="10"></textarea>
<br/>
<button onclick="compile()">Compile</button>
<br/>
<textarea id="compiledArray"  cols="40" rows="10" readonly></textarea></code>```

"VM" Specifications

The VM has 3 32 bit unsigned integral registers: R0, R1, R2. They are represented in hex as 0x00, 0x01, and 0x02.

The following operations must be supported:

The format is [name] [...operands...], [hexadecimal op-code] [...operands repeated...]

LOAD [register] [4 byte value], 0x00 [register] [4 byte value]

PUSH [register], 0x02 [register]

POP [register], 0x03 [register]

ADD [register, 1 byte] [register, 1 byte], 0x04 [register] [register]

SUB [register, 1 byte] [register, 1 byte], 0x05 [register] [register]

MUL [register, 1 byte] [register, 1 byte], 0x06 [register] [register]

DIV [register, 1 byte] [register, 1 byte], 0x07 [register] [register]

JMP [code line, 4 bytes], 0x08 [4 byte code line number]

CMP [register, 1 byte] [register, 1 byte], 0x09 [register] [register]

BRANCHLT [code line, 4 bytes], 0x0a [4 byte code line number]

Some notes:

The above math operations add the values of 2 registers together, placing the output in the first register.

CMP, the comparison operator, should compare the values of 2 registers and store the output in some internal flag (this can be implementation specific) for future use on branch instructions.

If BRANCH is called before CMP, unless BRANCHEQ is called, the "VM" should not branch.

PUSH/POP unsurprisingly push or pop numbers from the stack.

Jump and Branch operators jump to a specific operation (line of code), not a binary address.

Branch operations do not do the comparison. Rather, they take the output from the last comparison to execute.

Branch and Jump operators use a zero based line number indexing system. (E.g. JMP 0 jumps to the first line)

All operations are to be performed on unsigned numbers which overflow to zero and do not throw an exception on an integer overflow.

Division by zero is not allowed and as such, the behavior of the program is not defined. You can (for example)...

Crash the program.

End execution of the VM and return it's current state.

Show a "ERR: Division by 0" message.

Termination of the program is defined as when the instruction pointer reaches the end of the program (a non empty program can be assumed).

Output
The output must be exactly this (newlines included)

```<code>R0 3126900366
R1 0
R2 10000
</code>```

Points
Points are calculated based on the following formula: Number Of Characters * (Seconds Needed To Run / 2)

To avoid hardware differences causing different times, each test will be run on my computer (i5-4210u, 8GB ram) in either ubuntu server or Windows 8, so try not to use some insane-exotic-runtime that only compiles on a Dual G5 Mac Pro with exactly 762.66 mb of free RAM.

If you are using a specialized runtime/language, please post a link to it.

For interested parties, I have posted the testing code (written in C#) here: http://pastebin.com/WYCG5Uqu

Test Program

The idea came from here, so we'll use a somewhat modified version of their program.

The correct output for the program is: 3,126,900,366

In C:

```<code>int s, i, j;
for (s = 0, i = 0; i < 10000; i++) {
    for (j = 0; j < 10000; j++)
        s += (i * j) / 3;
}
</code>```

In code:
[R0 is representative of s, R1 of j, R2 of i]

```<code>LOAD R0 0
LOAD R2 0 <--outer loop value
LOAD R1 0 <--inner loop value
     --Begin inner loop--
PUSH R1 <--push inner loop value to the stack
MUL R1 R2 <--(i*j)
PUSH R2
LOAD R2 3
DIV R1 R2 <-- / 3
POP R2
ADD R0 R1 <-- s+=
POP R1
PUSH R2
LOAD R2 1
ADD R1 R2 <--j++
POP R2
PUSH R2
LOAD R2 10000
CMP R1 R2 <-- j < 10000
POP R2
BRANCHLT 3 <--Go back to beginning inner loop
--Drop To outer loop--
LOAD R1 1
ADD R2 R1 <--i++
LOAD R1 10000
CMP R2 R1 <-- i < 10000
LOAD R1 0 <--Reset inner loop
BRANCHLT 2
</code>```

In binary/hex:

```<code>0x00 0x00 0x00 0x00 0x00 0x00
0x00 0x02 0x00 0x00 0x00 0x00
0x00 0x01 0x00 0x00 0x00 0x00
0x02 0x01
0x06 0x01 0x02
0x02 0x02
0x00 0x02 0x00 0x00 0x00 0x03
0x07 0x01 0x02
0x03 0x02
0x04 0x00 0x01
0x03 0x01
0x02 0x02
0x00 0x02 0x00 0x00 0x00 0x01
0x04 0x01 0x02
0x03 0x02
0x02 0x02
0x00 0x02 0x00 0x00 0x27 0x10
0x09 0x01 0x02
0x03 0x02
0x0a 0x00 0x00 0x00 0x03
0x00 0x01 0x00 0x00 0x00 0x01
0x04 0x02 0x01
0x00 0x01 0x00 0x00 0x27 0x10
0x09 0x02 0x01
0x00 0x01 0x00 0x00 0x00 0x00
0x0a 0x00 0x00 0x00 0x02
</code>```

Bonus Points
 (Effects are applied multiplicatively) E.g. if you qualify for all three, it would be ((characters * 0.50) * 0.75) * 0.90

50% decrease if the interpreter is actually a JIT compiler

25% decrease if it applies any sort of loop unrolling/meaningful optimization.

10% decrease if you extend the VM with

BRANCHEQ [code line, 4 bytes] (Branch if equal - opcode 0x0b)

BRANCHGT [code line, 4 bytes] (Branch if greater than - opcode 0x0c)

BRANCHNE [code line, 4 bytes] (Branch if not equal - opcode 0x0d)

RLOAD [register 1] [register 2] (move the value of register 2 to register 1 - opcode 0x01).

Disallowed

Precompiling the test case into the program is prohibited. You must either accept the bytecode from STDIN or from a file (Doesn't matter which).

Returning the output without running the program.

Any other way you can think of to cheat the VM requirement.

答:
C#

1505 1475 bytes

This is my version of the interpreter, written in C# could be optimized / golfed more I think, but I don't really know where ;)

golfed version:

```<code>using System;using System.Collections.Generic;using System.IO;using System.Linq;class M{static void Main(string[]a){if(a.Length==1&&File.Exists(a[0])){B.E(B.P(File.ReadAllLines(a[0])));Console.WriteLine(B.O);}}}class B{public enum I{L=0x00,P=0x02,Q=0x03,A=0x04,S=0x05,M=0x06,D=0x07,J=0x08,C=0x09,BL=0x0a,BE=0x0b,BG=0x0c,BN=0x0d}public enum R{A,B,C}enum C{N,L,E,G}public static Dictionary<R,uint>r=new Dictionary<R,uint>{{R.A,0},{R.B,0},{R.C,0}};public static Stack<uint>s=new Stack<uint>();static C c=C.N;public static string O{get{return string.Format("R0 {0}\nR1 {1}\nR2 {2}",r[R.A],r[R.B],r[R.C]);}}public static void E(byte[][]l){for(uint i=0;i<l.Length;i++){var q=l[i];switch((I)q[0]){case I.L:r[(R)q[1]]=U(q,2);break;case I.P:r[(R)q[1]]=s.Pop();break;case I.Q:s.Push(r[(R)q[1]]);r[(R)q[1]]=0;break;case I.A:s.Push(r[(R)q[1]]+r[(R)q[2]]);break;case I.S:s.Push(r[(R)q[1]]-r[(R)q[2]]);break;case I.M:s.Push(r[(R)q[1]]*r[(R)q[2]]);break;case I.D:s.Push(r[(R)q[1]]/r[(R)q[2]]);break;case I.J:i=U(q,1)-1;break;case I.C:{uint x=r[(R)q[1]],y=r[(R)q[2]];c=x<y?C.L:x>y?C.G:C.E;}break;case I.BL:if(c==C.L)i=U(q,1)-1;break;case I.BG:if(c==C.G)i=U(q,1)-1;break;case I.BE:if(c==C.E)i=U(q,1)-1;break;case I.BN:if(c!=C.E)i=U(q,1)-1;break;}}}public static byte[][]P(string[]c){return c.Where(l=>!l.StartsWith("#")).Select(r=>r.Split(' ').Where(b=>b.Length>0).Select(b=>Convert.ToByte(b,16)).ToArray()).Where(l=>l.Length>0).ToArray();}static uint U(byte[]b,int i){return(uint)(b[i]<<24|b[i+1]<<16|b[i+2]<<8|b[i+3]);}}
</code>```

edit

removed some unnecessary public and private modifiers:

```<code>using System;using System.Collections.Generic;using System.IO;using System.Linq;class M{static void Main(string[]a){if(a.Length==1&&File.Exists(a[0])){B.E(B.P(File.ReadAllLines(a[0])));Console.Write(B.O);}}}class B{enum I{L=0x00,P=0x02,Q=0x03,A=0x04,S=0x05,M=0x06,D=0x07,J=0x08,C=0x09,BL=0x0a,BE=0x0b,BG=0x0c,BN=0x0d}enum R{A,B,C}enum C{N,L,E,G}static Dictionary<R,uint>r=new Dictionary<R,uint>{{R.A,0},{R.B,0},{R.C,0}};static Stack<uint>s=new Stack<uint>();static C c=C.N;public static string O{get{return string.Format("R0 {0}\nR1 {1}\nR2 {2}\n",r[R.A],r[R.B],r[R.C]);}}public static void E(byte[][]l){for(uint i=0;i<l.Length;i++){var q=l[i];switch((I)q[0]){case I.L:r[(R)q[1]]=U(q,2);break;case I.P:r[(R)q[1]]=s.Pop();break;case I.Q:s.Push(r[(R)q[1]]);r[(R)q[1]]=0;break;case I.A:s.Push(r[(R)q[1]]+r[(R)q[2]]);break;case I.S:s.Push(r[(R)q[1]]-r[(R)q[2]]);break;case I.M:s.Push(r[(R)q[1]]*r[(R)q[2]]);break;case I.D:s.Push(r[(R)q[1]]/r[(R)q[2]]);break;case I.J:i=U(q,1)-1;break;case I.C:{uint x=r[(R)q[1]],y=r[(R)q[2]];c=x<y?C.L:x>y?C.G:C.E;}break;case I.BL:if(c==C.L)i=U(q,1)-1;break;case I.BG:if(c==C.G)i=U(q,1)-1;break;case I.BE:if(c==C.E)i=U(q,1)-1;break;case I.BN:if(c!=C.E)i=U(q,1)-1;break;}}}public static byte[][]P(string[]c){return c.Where(l=>!l.StartsWith("#")).Select(r=>r.Split(' ').Where(b=>b.Length>0).Select(b=>Convert.ToByte(b,16)).ToArray()).Where(l=>l.Length>0).ToArray();}static uint U(byte[]b,int i){return(uint)(b[i]<<24|b[i+1]<<16|b[i+2]<<8|b[i+3]);}}
</code>```

call it with executable.exe filename where filename is the file containing the code to be interpreted

My "test program":

```<code># LOAD R0 5
# CMP R0 R1
# BRANCHEQ 13
# LOAD R1 1
# LOAD R2 1
# CMP R0 R2
# MUL R1 R2
# LOAD R1 1
# ADD R2 R1
# PUSH R2
# PUSH R1
# BRANCHEQ 13
# JMP 5
# POP R2
# POP R0
# POP R1
# PUSH R0

0x0 0x0 0x0 0x0 0x0 0x5
0x9 0x0 0x1
0xb 0x0 0x0 0x0 0xd
0x0 0x1 0x0 0x0 0x0 0x1
0x0 0x2 0x0 0x0 0x0 0x1
0x9 0x0 0x2
0x6 0x1 0x2
0x0 0x1 0x0 0x0 0x0 0x1
0x4 0x2 0x1
0x2 0x2
0x2 0x1
0xb 0x0 0x0 0x0 0xd
0x8 0x0 0x0 0x0 0x5
0x3 0x2
0x3 0x0
0x3 0x1
0x2 0x0
</code>```

Interpreter ungolfed with longer names variables, classes, ...

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        if (args.Length == 1 && File.Exists(args[0]))
        {
            var code = ByteCodeInterpreter.ParseCode(File.ReadAllLines(args[0]));
            ByteCodeInterpreter.Execute(code);
            Console.WriteLine(ByteCodeInterpreter.Output);
        }
    }
}

public static class ByteCodeInterpreter
{
    public enum Instruction : byte
    {
        LOAD = 0x00,
        PUSH = 0x02,
        POP = 0x03,
        ADD = 0x04,
        SUB = 0x05,
        MUL = 0x06,
        DIV = 0x07,
        JMP = 0x08,
        CMP = 0x09,
        BRANCHLT = 0x0a,
        BRANCHEQ = 0x0b,
        BRANCHGT = 0x0c,
        BRANCHNE = 0x0d
    }

    public enum Register : byte
    {
        R0 = 0x00,
        R1 = 0x01,
        R2 = 0x02
    }

    private enum CompareFlag : byte
    {
        NONE = 0x00,
        LT = 0x01,
        EQ = 0x02,
        GT = 0x03,
    }

    public static readonly Dictionary<Register, uint> register = new Dictionary<Register, uint>
    {
        {Register.R0, 0},
        {Register.R1, 0},
        {Register.R2, 0}
    };

    public static readonly Stack<uint> stack = new Stack<uint>();
    private static CompareFlag compareFlag = CompareFlag.NONE;

    public static string Output
    {
        get
        {
            return string.Format("R0 {0}\nR1 {1}\nR2 {2}", register[Register.R0], register[Register.R1],
                register[Register.R2]);
        }
    }

    public static void Execute(byte[][] lines)
    {
        for (uint i = 0; i < lines.Length; i++)
        {
            var line = lines[i];
            switch ((Instruction)line[0])
            {
                case Instruction.LOAD:
                    register[(Register)line[1]] = GetUint(line, 2);
                    break;
                case Instruction.PUSH:
                    register[(Register)line[1]] = stack.Pop();
                    break;
                case Instruction.POP:
                    stack.Push(register[(Register)line[1]]);
                    register[(Register)line[1]] = 0;
                    break;
                case Instruction.ADD:
                    stack.Push(register[(Register)line[1]] + register[(Register)line[2]]);
                    break;
                case Instruction.SUB:
                    stack.Push(register[(Register)line[1]] - register[(Register)line[2]]);
                    break;
                case Instruction.MUL:
                    stack.Push(register[(Register)line[1]] * register[(Register)line[2]]);
                    break;
                case Instruction.DIV:
                    stack.Push(register[(Register)line[1]] / register[(Register)line[2]]);
                    break;
                case Instruction.JMP:
                    i = GetUint(line, 1) - 1;
                    break;
                case Instruction.CMP:
                    {
                        uint v0 = register[(Register)line[1]], v1 = register[(Register)line[2]];
                        if (v0 < v1)
                            compareFlag = CompareFlag.LT;
                        else if (v0 > v1)
                            compareFlag = CompareFlag.GT;
                        else
                            compareFlag = CompareFlag.EQ;
                    }
                    break;
                case Instruction.BRANCHLT:
                    if (compareFlag == CompareFlag.LT)
                        i = GetUint(line, 1) - 1;
                    break;
                case Instruction.BRANCHGT:
                    if (compareFlag == CompareFlag.GT)
                        i = GetUint(line, 1) - 1;
                    break;
                case Instruction.BRANCHEQ:
                    if (compareFlag == CompareFlag.EQ)
                        i = GetUint(line, 1) - 1;
                    break;
                case Instruction.BRANCHNE:
                    if (compareFlag != CompareFlag.EQ)
                        i = GetUint(line, 1) - 1;
                    break;
            }
        }
    }

    public static byte[][] ParseCode(string[] code)
    {
        return
            code.Where(line => !line.StartsWith("#"))
                .Select(line => line.Split(' ').Where(b => b.Length > 0).Select(b => Convert.ToByte(b, 16)).ToArray())
                .Where(line => line.Length > 0)
                .ToArray();
    }

    private static uint GetUint(byte[] bytes, int index)
    {
        return (uint)(bytes[index] << 24 | bytes[index + 1] << 16 | bytes[index + 2] << 8 | bytes[index + 3]);
    }
}
</code>```

Title: Smallest Bytecode Interpreter/VM

Body:
C#

1505 1475 bytes

This is my version of the interpreter, written in C# could be optimized / golfed more I think, but I don't really know where ;)

golfed version:

using System;using System.Collections.Generic;using System.IO;using System.Linq;class M{static void Main(string[]a){if(a.Length==1&&File.Exists(a[0])){B.E(B.P(File.ReadAllLines(a[0])));Console.WriteLine(B.O);}}}class B{public enum I{L=0x00,P=0x02,Q=0x03,A=0x04,S=0x05,M=0x06,D=0x07,J=0x08,C=0x09,BL=0x0a,BE=0x0b,BG=0x0c,BN=0x0d}public enum R{A,B,C}enum C{N,L,E,G}public static Dictionary<R,uint>r=new Dictionary<R,uint>{{R.A,0},{R.B,0},{R.C,0}};public static Stack<uint>s=new Stack<uint>();static C c=C.N;public static string O{get{return string.Format("R0 {0}\nR1 {1}\nR2 {2}",r[R.A],r[R.B],r[R.C]);}}public static void E(byte[][]l){for(uint i=0;i<l.Length;i++){var q=l[i];switch((I)q[0]){case I.L:r[(R)q[1]]=U(q,2);break;case I.P:r[(R)q[1]]=s.Pop();break;case I.Q:s.Push(r[(R)q[1]]);r[(R)q[1]]=0;break;case I.A:s.Push(r[(R)q[1]]+r[(R)q[2]]);break;case I.S:s.Push(r[(R)q[1]]-r[(R)q[2]]);break;case I.M:s.Push(r[(R)q[1]]*r[(R)q[2]]);break;case I.D:s.Push(r[(R)q[1]]/r[(R)q[2]]);break;case I.J:i=U(q,1)-1;break;case I.C:{uint x=r[(R)q[1]],y=r[(R)q[2]];c=x<y?C.L:x>y?C.G:C.E;}break;case I.BL:if(c==C.L)i=U(q,1)-1;break;case I.BG:if(c==C.G)i=U(q,1)-1;break;case I.BE:if(c==C.E)i=U(q,1)-1;break;case I.BN:if(c!=C.E)i=U(q,1)-1;break;}}}public static byte[][]P(string[]c){return c.Where(l=>!l.StartsWith("#")).Select(r=>r.Split(' ').Where(b=>b.Length>0).Select(b=>Convert.ToByte(b,16)).ToArray()).Where(l=>l.Length>0).ToArray();}static uint U(byte[]b,int i){return(uint)(b[i]<<24|b[i+1]<<16|b[i+2]<<8|b[i+3]);}}

edit

removed some unnecessary public and private modifiers:

using System;using System.Collections.Generic;using System.IO;using System.Linq;class M{static void Main(string[]a){if(a.Length==1&&File.Exists(a[0])){B.E(B.P(File.ReadAllLines(a[0])));Console.Write(B.O);}}}class B{enum I{L=0x00,P=0x02,Q=0x03,A=0x04,S=0x05,M=0x06,D=0x07,J=0x08,C=0x09,BL=0x0a,BE=0x0b,BG=0x0c,BN=0x0d}enum R{A,B,C}enum C{N,L,E,G}static Dictionary<R,uint>r=new Dictionary<R,uint>{{R.A,0},{R.B,0},{R.C,0}};static Stack<uint>s=new Stack<uint>();static C c=C.N;public static string O{get{return string.Format("R0 {0}\nR1 {1}\nR2 {2}\n",r[R.A],r[R.B],r[R.C]);}}public static void E(byte[][]l){for(uint i=0;i<l.Length;i++){var q=l[i];switch((I)q[0]){case I.L:r[(R)q[1]]=U(q,2);break;case I.P:r[(R)q[1]]=s.Pop();break;case I.Q:s.Push(r[(R)q[1]]);r[(R)q[1]]=0;break;case I.A:s.Push(r[(R)q[1]]+r[(R)q[2]]);break;case I.S:s.Push(r[(R)q[1]]-r[(R)q[2]]);break;case I.M:s.Push(r[(R)q[1]]*r[(R)q[2]]);break;case I.D:s.Push(r[(R)q[1]]/r[(R)q[2]]);break;case I.J:i=U(q,1)-1;break;case I.C:{uint x=r[(R)q[1]],y=r[(R)q[2]];c=x<y?C.L:x>y?C.G:C.E;}break;case I.BL:if(c==C.L)i=U(q,1)-1;break;case I.BG:if(c==C.G)i=U(q,1)-1;break;case I.BE:if(c==C.E)i=U(q,1)-1;break;case I.BN:if(c!=C.E)i=U(q,1)-1;break;}}}public static byte[][]P(string[]c){return c.Where(l=>!l.StartsWith("#")).Select(r=>r.Split(' ').Where(b=>b.Length>0).Select(b=>Convert.ToByte(b,16)).ToArray()).Where(l=>l.Length>0).ToArray();}static uint U(byte[]b,int i){return(uint)(b[i]<<24|b[i+1]<<16|b[i+2]<<8|b[i+3]);}}

call it with executable.exe filename where filename is the file containing the code to be interpreted

My "test program":

# LOAD R0 5
# CMP R0 R1
# BRANCHEQ 13
# LOAD R1 1
# LOAD R2 1
# CMP R0 R2
# MUL R1 R2
# LOAD R1 1
# ADD R2 R1
# PUSH R2
# PUSH R1
# BRANCHEQ 13
# JMP 5
# POP R2
# POP R0
# POP R1
# PUSH R0

0x0 0x0 0x0 0x0 0x0 0x5
0x9 0x0 0x1
0xb 0x0 0x0 0x0 0xd
0x0 0x1 0x0 0x0 0x0 0x1
0x0 0x2 0x0 0x0 0x0 0x1
0x9 0x0 0x2
0x6 0x1 0x2
0x0 0x1 0x0 0x0 0x0 0x1
0x4 0x2 0x1
0x2 0x2
0x2 0x1
0xb 0x0 0x0 0x0 0xd
0x8 0x0 0x0 0x0 0x5
0x3 0x2
0x3 0x0
0x3 0x1
0x2 0x0

Interpreter ungolfed with longer names variables, classes, ...

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        if (args.Length == 1 && File.Exists(args[0]))
        {
            var code = ByteCodeInterpreter.ParseCode(File.ReadAllLines(args[0]));
            ByteCodeInterpreter.Execute(code);
            Console.WriteLine(ByteCodeInterpreter.Output);
        }
    }
}

public static class ByteCodeInterpreter
{
    public enum Instruction : byte
    {
        LOAD = 0x00,
        PUSH = 0x02,
        POP = 0x03,
        ADD = 0x04,
        SUB = 0x05,
        MUL = 0x06,
        DIV = 0x07,
        JMP = 0x08,
        CMP = 0x09,
        BRANCHLT = 0x0a,
        BRANCHEQ = 0x0b,
        BRANCHGT = 0x0c,
        BRANCHNE = 0x0d
    }

    public enum Register : byte
    {
        R0 = 0x00,
        R1 = 0x01,
        R2 = 0x02
    }

    private enum CompareFlag : byte
    {
        NONE = 0x00,
        LT = 0x01,
        EQ = 0x02,
        GT = 0x03,
    }

    public static readonly Dictionary<Register, uint> register = new Dictionary<Register, uint>
    {
        {Register.R0, 0},
        {Register.R1, 0},
        {Register.R2, 0}
    };

    public static readonly Stack<uint> stack = new Stack<uint>();
    private static CompareFlag compareFlag = CompareFlag.NONE;

    public static string Output
    {
        get
        {
            return string.Format("R0 {0}\nR1 {1}\nR2 {2}", register[Register.R0], register[Register.R1],
                register[Register.R2]);
        }
    }

    public static void Execute(byte[][] lines)
    {
        for (uint i = 0; i < lines.Length; i++)
        {
            var line = lines[i];
            switch ((Instruction)line[0])
            {
                case Instruction.LOAD:
                    register[(Register)line[1]] = GetUint(line, 2);
                    break;
                case Instruction.PUSH:
                    register[(Register)line[1]] = stack.Pop();
                    break;
                case Instruction.POP:
                    stack.Push(register[(Register)line[1]]);
                    register[(Register)line[1]] = 0;
                    break;
                case Instruction.ADD:
                    stack.Push(register[(Register)line[1]] + register[(Register)line[2]]);
                    break;
                case Instruction.SUB:
                    stack.Push(register[(Register)line[1]] - register[(Register)line[2]]);
                    break;
                case Instruction.MUL:
                    stack.Push(register[(Register)line[1]] * register[(Register)line[2]]);
                    break;
                case Instruction.DIV:
                    stack.Push(register[(Register)line[1]] / register[(Register)line[2]]);
                    break;
                case Instruction.JMP:
                    i = GetUint(line, 1) - 1;
                    break;
                case Instruction.CMP:
                    {
                        uint v0 = register[(Register)line[1]], v1 = register[(Register)line[2]];
                        if (v0 < v1)
                            compareFlag = CompareFlag.LT;
                        else if (v0 > v1)
                            compareFlag = CompareFlag.GT;
                        else
                            compareFlag = CompareFlag.EQ;
                    }
                    break;
                case Instruction.BRANCHLT:
                    if (compareFlag == CompareFlag.LT)
                        i = GetUint(line, 1) - 1;
                    break;
                case Instruction.BRANCHGT:
                    if (compareFlag == CompareFlag.GT)
                        i = GetUint(line, 1) - 1;
                    break;
                case Instruction.BRANCHEQ:
                    if (compareFlag == CompareFlag.EQ)
                        i = GetUint(line, 1) - 1;
                    break;
                case Instruction.BRANCHNE:
                    if (compareFlag != CompareFlag.EQ)
                        i = GetUint(line, 1) - 1;
                    break;
            }
        }
    }

    public static byte[][] ParseCode(string[] code)
    {
        return
            code.Where(line => !line.StartsWith("#"))
                .Select(line => line.Split(' ').Where(b => b.Length > 0).Select(b => Convert.ToByte(b, 16)).ToArray())
                .Where(line => line.Length > 0)
                .ToArray();
    }

    private static uint GetUint(byte[] bytes, int index)
    {
        return (uint)(bytes[index] << 24 | bytes[index + 1] << 16 | bytes[index + 2] << 8 | bytes[index + 3]);
    }
}


问:
Export The $PATH Variable, Line-By-Line
Inspired by this question on AskUbuntu.

Your job is extremely simple. Take the PATH environment variable (echo $PATH) and export it such that each entry (separated by the : character) is on its own line.

For example, if the PATH is /bin:/usr/bin:/usr/local/bin, your program should output:

```<code>/bin
/usr/bin
/usr/local/bin
</code>```

Your program may not return a leading newline, but it may return a single trailing newline. You do not need to check if the PATH is right, or that the directory exists. Your program should take no input, meaning that your program is responsible for getting the PATH itself. You may safely assume that objects in the PATH do not contain : or newlines. However, spaces are fair game.

Reference implementations are present in the answers to the question above.

Rules

This is (obviously) code-golf, so the shortest answer will win the prized green checkmark.

The accepted answer will be tested to make sure it's actually legit.

Both Windows and *nix entries are accepted.

However, if you don't explicitly specify Windows, I will try running it in Linux and fail. (If it's obvious (hi, Batch!), you don't need to specify explicitly.)

Only have one solution per answer. If you have both a Windows and *nix version, I will count the shorter one.

If two answers have the same length, I will give priority to the one with the higher vote total. If they have the same vote total, I will count the older one. If the time posted is the same, I will choose the one that executes faster. If they execute in the same amount of time, I don't know.

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
R, 38 bytes

```<code>cat(gsub(":","\n",Sys.getenv('PATH')))
</code>```

Grab the $PATH, replace : with newlines and prints to stdout. You can try it online here.

ContentLicense: CC BY-SA 3.0

Title: Export The $PATH Variable, Line-By-Line

Body:
R, 38 bytes

cat(gsub(":","\n",Sys.getenv('PATH')))

Grab the $PATH, replace : with newlines and prints to stdout. You can try it online here.


问:
Letter-replacement challenge
The idea is simple. You've to create a "visualised" letter-replacement, by providing 3 strings (input can be comma separated, separate inputs, or as an array). The first segment is the word you want to correct, and the second segment is the letters you want to replace, and the third segment is the replacement for the letters in segment 2.

For example:

```<code>|    | Input                       | Starting Word | Output      |
|----|-----------------------------|---------------|-------------|
| #1 | Hello world -wo -ld +Ea +th | Hello world   | Hello Earth |
| #2 | Hello World -wo -ld +Ea +th | Hello World   | Hello Worth |
| #3 | Hello -llo +y               | Hello         | Hey         |
| #4 | Red -R -d +Gr +en           | Red           | Green       |
| #5 | mississippi -is -i +lz +p   | mississippi   | mlzslzspppp |
| #6 | Football -o -a +a +i        | Football      | Fiitbill    |
| #7 | mississippi -is -i +iz +p   | mississippi   | mpzspzspppp |
</code>```

Explanation

The replacements are to be done step-by-step with their respective pair. Here's an illustration with an input of mississippi -is -i +iz +p to give the output mpzspzsppp (see example #7 above)

```<code>| Step  | Input                         | Output        |
|------ |---------------------------    |-------------  |
| #1    | mississippi -is -i +iz +p     |               |
| #2    | mississippi -is +iz           | mizsizsippi   |
| #3    | mizsizsippi -i +p             | mpzspzspppp   |
</code>```

Rules

Inputs are always in this order <starting_string> <list_of_letters_to_replace> <replacement_letters>.

Letters to replace and replacement groups will never be mixed (ie: there will never be -a +i -e +o).

Letters to replace are always prefixed with - and replacement letters are always prefixed with +. (The prefix is mandatory)

There may be more than one set of letters to replace, so you'd need to look at the prefix.

Assume the amount of letter groups to replace and the amount of replacement letter groups are always equal (ie: there will never be -a -e +i)

Replacements are case-sensitive (see example #1 and #2).

Replacements are done in the order they were given in the input.

Letter replacements can be replaced with other replacements. See example #6.

The first segment (starting word) will never include - or + characters.

This is code-golf so shortest bytes win.

Leaderboards

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

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>```

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
PowerShell v2+, 90 bytes

```<code>param($a,$b,$c)-split$b|%{$a=$a-creplace($_-replace'-'),((-split$c)[$i++]-replace'\+')};$a
</code>```

Takes input as three arguments, with the - and + strings space-separated. Performs a -split on $b (the -split when acting in a unary fashion splits on whitespace), then loops |%{...} through each of those. Every iteration we're removing the -, finding the next [$i++] replacement string and removing the + from it, and using the -creplace (case-sensitive replacement) to slice and dice $a and store it back into $a. Then, $a is left on the pipeline and output is implicit.

```<code>PS C:\Tools\Scripts\golfing> .\letter-replacement-challenge.ps1 'mississippi' '-is -i' '+iz +p'
mpzspzspppp

PS C:\Tools\Scripts\golfing> .\letter-replacement-challenge.ps1 'Hello world' '-wo -ld' '+Ea +th'
Hello Earth

PS C:\Tools\Scripts\golfing> .\letter-replacement-challenge.ps1 'Hello World' '-wo -ld' '+Ea +th'
Hello Worth
</code>```

Title: Letter-replacement challenge

Body:
PowerShell v2+, 90 bytes

param($a,$b,$c)-split$b|%{$a=$a-creplace($_-replace'-'),((-split$c)[$i++]-replace'\+')};$a

Takes input as three arguments, with the - and + strings space-separated. Performs a -split on $b (the -split when acting in a unary fashion splits on whitespace), then loops |%{...} through each of those. Every iteration we're removing the -, finding the next [$i++] replacement string and removing the + from it, and using the -creplace (case-sensitive replacement) to slice and dice $a and store it back into $a. Then, $a is left on the pipeline and output is implicit.

PS C:\Tools\Scripts\golfing> .\letter-replacement-challenge.ps1 'mississippi' '-is -i' '+iz +p'
mpzspzspppp

PS C:\Tools\Scripts\golfing> .\letter-replacement-challenge.ps1 'Hello world' '-wo -ld' '+Ea +th'
Hello Earth

PS C:\Tools\Scripts\golfing> .\letter-replacement-challenge.ps1 'Hello World' '-wo -ld' '+Ea +th'
Hello Worth


问:
Display a Connect Four game
Connect Four is a game where two players take turns to drop disks into columns of a vertically mounted grid, and attempt to connect four disks orthogonally or diagonally. When a column is chosen, the disk falls to the lowest empty position in that column, so any game may be completely specified by the size of the grid and the sequence of columns chosen. The task is to generate the configuration of the grid given this information.

Input

Width w and Height h of the grid, both positive integers.

Sequence of columns c1, c2, ..., cn chosen by the players, in any reasonable format (list, array etc.); either 0-based (0 to w-1) or 1-based (1 to w) indexing can be used.

It may be assumed that all of the column numbers lie within the grid (so the sequence won't contain -3 or w+50) and that any column number appears at most h times in the sequence (so a column can't be chosen once it is full).

Note that the sequence of columns may not constitute a complete game, nor a legal game. For instance, the players could opt to continue playing even after a player has connected four disks.

Output

Any reasonable representation of the resulting state of each position in the grid, either "occupied by Player 1", "occupied by Player 2", or "empty". Player 1 always moves first.

For example, a string, array, tuple etc. with each position containing one of three symbols (ASCII character, number etc.) representing the state of that position in the grid. The grid may be transposed.

For list/tuple/array outputs, the separator cannot be one of the three representative symbols. For string outputs, trailing spaces at the end of each line are permitted, provided a space is not one of the three representative symbols. Trailing newlines at the very end are permitted.

Test cases

Here, string output is used, with X, O, . denoting "occupied by Player 1", "occupied by Player 2", "empty".

```<code>IN: Width 1 Height 1 Sequence (empty sequence)
OUT:
.

IN: Width 7 Height 6 Sequence 4 4 5 5 6 7 3 [1-based]
                              3 3 4 4 5 6 2 [0-based]
OUT:
.......
.......
.......
.......
...OO..
..XXXXO

IN: Width 5 Height 5 Sequence 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 [1-based]
                              0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 [0-based]
OUT:
XOXOX
OXOXO
XOXOX
OXOXO
xOXOX

IN: Width 4 Height 4 Sequence 3 3 2 4 3 2 4 2 2 3 4 4 1 1 1 1 [1-based]
                              2 2 1 3 2 1 3 1 1 2 3 3 0 0 0 0 [0-based]
OUT:
OXOO
XOXX
OOOX
XXXO

IN: Width 10 Height 10 Sequence 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 10  [1-based]
                                0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0  9 0  9  [0-based]
OUT:
X.........
X.........
X.........
X.........
X.........
X.........
X.........
X.........
X........O
XOOOOOOOOO
</code>```

Shortest code in bytes wins.

答:
JavaScript (ES6), 62 <s>69</s>

Edit 7 bytes saved thx @Arnauld

I have used this kind of string representation when logging the board status in my connect four player. It's short coded and easy to understand at first sight.

Input is 0 based

(w,h,s)=>s.map((v,i)=>r[v]+=i&1,r=Array(w).fill`|`)&&r.join`
`
```
<p>More in line with the OP examples, this is 93 bytes</p>
<pre class="lang-js prettyprint-override"><code>(w,h,s)=>s.map((v,i)=>r[v]+=i%2,r=Array(w).fill(``))&&r.map(r=>r+Array(h+1-r.length)).join`
`
</code>```

(note: here the fill``  trick won't work)

Output for [7, 6, [3, 3, 4, 4, 5, 6, 2]]

,,,,,,
,,,,,,
0,,,,,
01,,,,
01,,,,
0,,,,,
1,,,,,
```
<p><strong>Test</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f=(w,h,s)=>s.map((v,i)=>r[v]+=i&1,r=Array(w).fill`|`)&&r.join`
`

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

;[
  [1, 1, []]
, [7, 6, [3, 3, 4, 4, 5, 6, 2]]
, [5, 5, [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4]]
, [4, 4, [2, 2, 1, 3, 2, 1, 3, 1, 1, 2, 3, 3, 0, 0, 0, 0]]
].forEach(t=>{
  var w=t[0],h=t[1],s=t[2],r=f(w,h,s)
  console.log(w+' '+h+' ['+s+']\n'+r+'\n')
})</code>```

```</code>```

Title: Display a Connect Four game

Body:
JavaScript (ES6), 62 <s>69</s>

Edit 7 bytes saved thx @Arnauld

I have used this kind of string representation when logging the board status in my connect four player. It's short coded and easy to understand at first sight.

Input is 0 based

(w,h,s)=>s.map((v,i)=>r[v]+=i&1,r=Array(w).fill`|`)&&r.join`
`

More in line with the OP examples, this is 93 bytes

(w,h,s)=>s.map((v,i)=>r[v]+=i%2,r=Array(w).fill(``))&&r.map(r=>r+Array(h+1-r.length)).join`
`

(note: here the fill``  trick won't work)

Output for [7, 6, [3, 3, 4, 4, 5, 6, 2]]

,,,,,,
,,,,,,
0,,,,,
01,,,,
01,,,,
0,,,,,
1,,,,,

Test

f=(w,h,s)=>s.map((v,i)=>r[v]+=i&1,r=Array(w).fill`|`)&&r.join`
`

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

;[
  [1, 1, []]
, [7, 6, [3, 3, 4, 4, 5, 6, 2]]
, [5, 5, [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4]]
, [4, 4, [2, 2, 1, 3, 2, 1, 3, 1, 1, 2, 3, 3, 0, 0, 0, 0]]
].forEach(t=>{
  var w=t[0],h=t[1],s=t[2],r=f(w,h,s)
  console.log(w+' '+h+' ['+s+']\n'+r+'\n')
})

<pre id=O></pre>


问:
How many answers does this question have?
Write a program or a function that outputs the integer number of answers this question has. Your solution should still work as more answers are added.

Languages that run in a browser may be run from the js console while on this page. Otherwise, you'd probably have to download this page. Multi-language solutions, e.g. wgeting the page and parsing it using grep is ok. Just sum up the command line and all source used.

This is code golf; shortest answer in bytes wins.

EDIT:

Let's allow at most one occourance of the url of this page to not count, either as input or in the source. No url shorteners, no data stored as get parameters etc. Quotes around url, if needed, still count. Taking the url as input is also fine. If you want to remove some part of the url, e.g. /how-many-answers..., you can, but it probably doesn't help you.

答:
Java, <s>230</s> 269-41=228 bytes

```<code>interface A{static void main(String[]a)throws Exception{System.out.print(new java.util.Scanner(new java.net.URL("http://codegolf.stackexchange.com/q/96298").openStream()).useDelimiter("\\Z").next().replaceAll("\n|\r","").replaceAll("^.+?\\s+(\\d+) Answers.+$","$1"));}}
</code>```

(Only counts non-deleted answers)

Body:
Java, <s>230</s> 269-41=228 bytes

interface A{static void main(String[]a)throws Exception{System.out.print(new java.util.Scanner(new java.net.URL("http://codegolf.stackexchange.com/q/96298").openStream()).useDelimiter("\\Z").next().replaceAll("\n|\r","").replaceAll("^.+?\\s+(\\d+) Answers.+$","$1"));}}

(Only counts non-deleted answers)


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

w,h,s=input()
i,x=0,['']*w
for c in s:x[c]+='XO'[i%2];i+=1
for c in x:print(c+'.'*h)[:h]
```

Since transposed is fine, this prints the board sitting on its right hand side.

repl.it

Title: Display a Connect Four game

Body:
Connect Four is a game where two players take turns to drop disks into columns of a vertically mounted grid, and attempt to connect four disks orthogonally or diagonally. When a column is chosen, the disk falls to the lowest empty position in that column, so any game may be completely specified by the size of the grid and the sequence of columns chosen. The task is to generate the configuration of the grid given this information.

Input

Width w and Height h of the grid, both positive integers.

Sequence of columns c1, c2, ..., cn chosen by the players, in any reasonable format (list, array etc.); either 0-based (0 to w-1) or 1-based (1 to w) indexing can be used.

It may be assumed that all of the column numbers lie within the grid (so the sequence won't contain -3 or w+50) and that any column number appears at most h times in the sequence (so a column can't be chosen once it is full).

Note that the sequence of columns may not constitute a complete game, nor a legal game. For instance, the players could opt to continue playing even after a player has connected four disks.

Output

Any reasonable representation of the resulting state of each position in the grid, either "occupied by Player 1", "occupied by Player 2", or "empty". Player 1 always moves first.

For example, a string, array, tuple etc. with each position containing one of three symbols (ASCII character, number etc.) representing the state of that position in the grid. The grid may be transposed.

For list/tuple/array outputs, the separator cannot be one of the three representative symbols. For string outputs, trailing spaces at the end of each line are permitted, provided a space is not one of the three representative symbols. Trailing newlines at the very end are permitted.

Test cases

Here, string output is used, with X, O, . denoting "occupied by Player 1", "occupied by Player 2", "empty".

```<code>IN: Width 1 Height 1 Sequence (empty sequence)
OUT:
.

IN: Width 7 Height 6 Sequence 4 4 5 5 6 7 3 [1-based]
                              3 3 4 4 5 6 2 [0-based]
OUT:
.......
.......
.......
.......
...OO..
..XXXXO

IN: Width 5 Height 5 Sequence 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 [1-based]
                              0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 [0-based]
OUT:
XOXOX
OXOXO
XOXOX
OXOXO
xOXOX

IN: Width 4 Height 4 Sequence 3 3 2 4 3 2 4 2 2 3 4 4 1 1 1 1 [1-based]
                              2 2 1 3 2 1 3 1 1 2 3 3 0 0 0 0 [0-based]
OUT:
OXOO
XOXX
OOOX
XXXO

IN: Width 10 Height 10 Sequence 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 10  [1-based]
                                0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0  9 0  9  [0-based]
OUT:
X.........
X.........
X.........
X.........
X.........
X.........
X.........
X.........
X........O
XOOOOOOOOO
</code>```

Shortest code in bytes wins.

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

w,h,s=input()
i,x=0,['']*w
for c in s:x[c]+='XO'[i%2];i+=1
for c in x:print(c+'.'*h)[:h]

Since transposed is fine, this prints the board sitting on its right hand side.

repl.it


问:
Nest a string inside an array n times
You must produce a function which nests a string s inside an array, n times

```<code>>>> N("stackoverflow",2)
[['stackoverflow']]
</code>```

Parameters:

s - An ascii string

n - An integer >= 0

Rules

Shortest code wins.

The output will be a nested array, list or tuple (or similar type based off an array)

Test Cases

```<code>>>> N("stackoverflow",0)
'stackoverflow'
>>> N("stackoverflow",1)
['stackoverflow']
>>> N("stackoverflow",5)
[[[[['stackoverflow']]]]]
</code>```

Inspired by: Nesting a string inside a list n times ie list of a list of a list

答:
C# 6, 50 bytes

```<code>dynamic a(dynamic s,int n)=>n<2?s:a(new[]{s},n-1);
</code>```

Title: Nest a string inside an array n times

Body:
C# 6, 50 bytes

dynamic a(dynamic s,int n)=>n<2?s:a(new[]{s},n-1);


问:
ASCII Odd/Even Cipher
We'll define the ASCII Odd/Even Cipher via the below pseudocode:

```<code>Define 'neighbor' as the characters adjacent to the current letter in the string

If the one of the neighbors is out of bounds of the string, treat it as \0 or null

Take an input string

For each letter in the string, do
  If the 0-based index of the current letter is even, then
    Use the binary-or of the ASCII codes of both its neighbors
  Else
    If the ASCII code of the current letter is odd, then
      Use the binary-or of itself plus the left neighbor
    Else
      Use the binary-or of itself plus the right neighbor
  In all cases,
    Convert the result back to ASCII and return it
  If this would result in a code point 127 or greater to be converted, then
    Instead return a space

Join the results of the For loop back into one string and output it
</code>```

For example, for input Hello, the output is emmol, since

The H turns to \0 | 'e' which is e

The e turns to 'e' | 'l', or 101 | 108, which is 109 or m

The first l also turns to 101 | 108 or m

The second l turns to 108 | 111, which is 111 or o

The o turns to 108 | \0, or l

Input

A sentence composed solely of printable ASCII characters, in any suitable format.

The sentence may have periods, spaces, and other punctuation, but will only ever be one line.

The sentence will be at least three characters in length.

Output

The resulting cipher, based on the rules described above, returned as a string or output.

The Rules

Either a full program or a function are acceptable.

Standard loopholes are forbidden.

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

Examples

Input on one line, output on the following. Blank lines separate examples.

```<code>Hello
emmol

Hello, World!
emmol, ww~ved

PPCG
PSWG

Programming Puzzles and Code Golf
r wogsmmoonpuu ~ meannncoooeggonl

abcdefghijklmnopqrstuvwxyz
bcfefgnijknmno~qrsvuvw~yzz

!abcdefghijklmnopqrstuvwxyz
aaccgeggoikkomoo qsswuww yy

Test 123 with odd characters. R@*SKA0z8d862
euutu133www|todddchizsscguwssr`jS{SK{z~|v66
</code>```

答:
C#, 145 bytes

```<code>s=>{var r=s[1]+"";int i=1,l=s.Length,c;for(;i<l;i++){c=i>l-2?0:s[i+1];c=i%2<1?s[i-1]|c:s[i]|(s[i]%2>0?s[i-1]:c);r+=c>'~'?' ':(char)c;}return r;};
</code>```

Full program with ungolfed method and test cases:

```<code>using System;

namespace ASCIIOddEvenCipher
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,string>f= s=>
            {
                var r = s[1] + "";
                int i = 1, l = s.Length, c;
                for(;i < l; i++)
                {
                    c = i>l-2 ? 0 : s[i+1];
                    c = i%2<1 ? s[i-1]|c : s[i]|(s[i]%2>0 ? s[i-1] : c);
                    r += c > '~' ? ' ' : (char)c;
                }
                return r;
            };

            //test cases:
            Console.WriteLine(f("Hello"));  //emmol
            Console.WriteLine(f("Hello, World!"));  //emmol, ww~ved
            Console.WriteLine(f("PPCG"));   //PSWG
            Console.WriteLine(f("Programming Puzzles and Code Golf"));  //r wogsmmoonpuu ~ meannncoooeggonl
            Console.WriteLine(f("abcdefghijklmnopqrstuvwxyz")); //bcfefgnijknmno~qrsvuvw~yzz
            Console.WriteLine(f("!abcdefghijklmnopqrstuvwxyz"));    //aaccgeggoikkomoo qsswuww yy
            Console.WriteLine(f("Test 123 with odd characters. R@*SKA0z8d862"));    //euutu133www|todddchizsscguwssr`jS{SK{z~|v66
        }
    }
}
</code>```

This turned out to be longer than I thought...

Title: ASCII Odd/Even Cipher

Body:
C#, 145 bytes

s=>{var r=s[1]+"";int i=1,l=s.Length,c;for(;i<l;i++){c=i>l-2?0:s[i+1];c=i%2<1?s[i-1]|c:s[i]|(s[i]%2>0?s[i-1]:c);r+=c>'~'?' ':(char)c;}return r;};

Full program with ungolfed method and test cases:

using System;

namespace ASCIIOddEvenCipher
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,string>f= s=>
            {
                var r = s[1] + "";
                int i = 1, l = s.Length, c;
                for(;i < l; i++)
                {
                    c = i>l-2 ? 0 : s[i+1];
                    c = i%2<1 ? s[i-1]|c : s[i]|(s[i]%2>0 ? s[i-1] : c);
                    r += c > '~' ? ' ' : (char)c;
                }
                return r;
            };

            //test cases:
            Console.WriteLine(f("Hello"));  //emmol
            Console.WriteLine(f("Hello, World!"));  //emmol, ww~ved
            Console.WriteLine(f("PPCG"));   //PSWG
            Console.WriteLine(f("Programming Puzzles and Code Golf"));  //r wogsmmoonpuu ~ meannncoooeggonl
            Console.WriteLine(f("abcdefghijklmnopqrstuvwxyz")); //bcfefgnijknmno~qrsvuvw~yzz
            Console.WriteLine(f("!abcdefghijklmnopqrstuvwxyz"));    //aaccgeggoikkomoo qsswuww yy
            Console.WriteLine(f("Test 123 with odd characters. R@*SKA0z8d862"));    //euutu133www|todddchizsscguwssr`jS{SK{z~|v66
        }
    }
}

This turned out to be longer than I thought...


答:
JavaScript (ES6), 121 bytes

```<code>(w,h,a,r=Array(w).fill``)=>a.map((c,j)=>r[c]+="XO"[j%2])&&[...Array(h)].map((_,i)=>r.map(s=>s[h+~i]||`.`).join``).join`\n`
</code>```

0-indexed. I wanted to see how well I could match the example output, but most of the code seems to be taken up by the rotation.

Title: Display a Connect Four game

Body:
JavaScript (ES6), 121 bytes

(w,h,a,r=Array(w).fill``)=>a.map((c,j)=>r[c]+="XO"[j%2])&&[...Array(h)].map((_,i)=>r.map(s=>s[h+~i]||`.`).join``).join`\n`

0-indexed. I wanted to see how well I could match the example output, but most of the code seems to be taken up by the rotation.


答:
Vim, 34 bytes

@wO-<Esc><C-V>(d@hpqq<C-O>+D@"G+bs<C-R>=!@.<CR><Esc>@qq@q

Input is width in the "w register, height in the "h register, and the 1-indexed moves in the buffer, one per line. Output is a transposed grid with - as blank, 1 as player 1, and 0 as player 2 (with a bunch of newlines at the end).

To clarify, if you want Height 6, Width 7: type qh6qqw7q before starting.

@wO-<Esc><C-V>(d@hp: Use the height and width in the registers to make a transposed grid of -s. Note that ( is run from the last line of the grid, one above the moves. This sets up the jump list.

<C-O>+D@"G: The <C-O> uses the jump list to move back to before the last G, always to the line above the next number. @"G moves to the line number indicated by the deleted text. + not only moves the cursor, but it's the failure point; when it runs on the last line, the macro dies.

+b: This maneuver goes to the first - in the line, even if it's the first character. (f- would go to the second character if the line was still all -s.)

s<C-R>=!@.: Replaces a - with the last insert @., but NOTted. First time through, the previous insert of - will NOT to 1 because that's the way Vim is. After that, it will alternate between 0 and 1.

Example

Start with the moves in the buffer:

```<code>4
4
5
5
6
7
3
</code>```

Make sure you're on line 1 with gg, clear "q with qqq, set up the registers for width 7, height 6 with qw7qqh6q. Then run the solution above and get the following output (with newlines at the end):

```<code>------
------
1-----
10----
10----
1-----
0-----
</code>```

Title: Display a Connect Four game

Body:
Vim, 34 bytes

@wO-<Esc><C-V>(d@hpqq<C-O>+D@"G+bs<C-R>=!@.<CR><Esc>@qq@q

Input is width in the "w register, height in the "h register, and the 1-indexed moves in the buffer, one per line. Output is a transposed grid with - as blank, 1 as player 1, and 0 as player 2 (with a bunch of newlines at the end).

To clarify, if you want Height 6, Width 7: type qh6qqw7q before starting.

@wO-<Esc><C-V>(d@hp: Use the height and width in the registers to make a transposed grid of -s. Note that ( is run from the last line of the grid, one above the moves. This sets up the jump list.

<C-O>+D@"G: The <C-O> uses the jump list to move back to before the last G, always to the line above the next number. @"G moves to the line number indicated by the deleted text. + not only moves the cursor, but it's the failure point; when it runs on the last line, the macro dies.

+b: This maneuver goes to the first - in the line, even if it's the first character. (f- would go to the second character if the line was still all -s.)

s<C-R>=!@.: Replaces a - with the last insert @., but NOTted. First time through, the previous insert of - will NOT to 1 because that's the way Vim is. After that, it will alternate between 0 and 1.

Example

Start with the moves in the buffer:

4
4
5
5
6
7
3

Make sure you're on line 1 with gg, clear "q with qqq, set up the registers for width 7, height 6 with qw7qqh6q. Then run the solution above and get the following output (with newlines at the end):

------
------
1-----
10----
10----
1-----
0-----


答:
Pyth, 3 bytes

```<code>]Fw
</code>```

Permalink

This will output something like ...[[[[['string']]]]].... It will not quote for zero depth: string.

Explanation:

```<code>]Fw
   Q Implicit: Eval first input line
]    Function: Wrap in array
  w  Input line
 F   Apply multiple times
</code>```

If you want quoting on zero depth, use this 4-byte solution instead (explanation):

```<code>`]Fw
    Q Implicit: Eval first input line
 ]    Function: Wrap in array
   w  Input line
  F   Apply multiple times
`     Representation
</code>```

Title: Nest a string inside an array n times

Body:
You must produce a function which nests a string s inside an array, n times

```<code>>>> N("stackoverflow",2)
[['stackoverflow']]
</code>```

Parameters:

s - An ascii string

n - An integer >= 0

Rules

Shortest code wins.

The output will be a nested array, list or tuple (or similar type based off an array)

Test Cases

```<code>>>> N("stackoverflow",0)
'stackoverflow'
>>> N("stackoverflow",1)
['stackoverflow']
>>> N("stackoverflow",5)
[[[[['stackoverflow']]]]]
</code>```

Inspired by: Nesting a string inside a list n times ie list of a list of a list

Body:
Pyth, 3 bytes

]Fw

Permalink

This will output something like ...[[[[['string']]]]].... It will not quote for zero depth: string.

Explanation:

]Fw
   Q Implicit: Eval first input line
]    Function: Wrap in array
  w  Input line
 F   Apply multiple times

If you want quoting on zero depth, use this 4-byte solution instead (explanation):

`]Fw
    Q Implicit: Eval first input line
 ]    Function: Wrap in array
   w  Input line
  F   Apply multiple times
`     Representation


答:
GNU sed 44 Bytes

Includes +1 for -r

```<code>s/(.*),(1*)/\2"\1"\2/
:;s/1(.*".*)1/[\1]/;t
</code>```

Try it online!

Takes the depth to nest the string as a unary number based on this consensus

Example:

```<code>$ echo 'stack"o,verflow,1111' | sed -rf nest.sed
[[[["stack"o,verflow"]]]]
</code>```

Title: Nest a string inside an array n times

Body:
GNU sed 44 Bytes

Includes +1 for -r

s/(.*),(1*)/\2"\1"\2/
:;s/1(.*".*)1/[\1]/;t

Try it online!

Takes the depth to nest the string as a unary number based on this consensus

Example:

$ echo 'stack"o,verflow,1111' | sed -rf nest.sed
[[[["stack"o,verflow"]]]]


问:
The Letter E with E
Your task is to display the below letter "E" shaped ASCII art, given five inputs.

Examples:

Input: 7,2,+,|,- (Note: You don't have to follow this exact input format, and if you don't use it, then you must explain how your own input format works)

Explanation:

7 total width, including the left and right edge characters.

2 Number of vertical characters.

+ The character that should display at the edges.

| The character that should display vertically between the edges.

- The character that should display horizontally.

Output of the above example:

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

Other examples:

Input: 7,2,@,|,-

Output:

```<code>@-----@
|
|
@-----@
|
|
@-----@
</code>```

Input: 7,2,+,|,#

Output:

```<code>+#####+
|
|
+#####+
|
|
+#####+
</code>```

Input: 8,3,+,|,#

Output:

```<code>+######+
|
|
|
+######+
|
|
|
+######+
</code>```

Input: 8,3,+,@,#

Output:

```<code>+######+
@
@
@
+######+
@
@
@
+######+
</code>```

Input: 9,4,^,$,!

Output:

```<code>^!!!!!!!^
$
$
$
$
^!!!!!!!^
$
$
$
$
^!!!!!!!^
</code>```

Cheating and standard loopholes are not allowed.

Your code must not print anything to STDERR.

Your code may accept any character encoding you choose as the input, but any character encoding you choose must, as a minimum, support all the 95 printable ASCII characters.

The shortest code, in bytes, that completes this challenge successfully, is the winning code.

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
PHP, 97 bytes

```<code>list(,$w,$h,$c,$v,$r)=$argv;echo$b=str_pad($a=str_pad($c,++$w,$r)."$c\n",--$h*2+$w,"$v\n"),$b,$a;
</code>```

no loop, only builtins.

Run with php -r '' <parameters>.

Title: The Letter E with E

Body:
PHP, 97 bytes

list(,$w,$h,$c,$v,$r)=$argv;echo$b=str_pad($a=str_pad($c,++$w,$r)."$c\n",--$h*2+$w,"$v\n"),$b,$a;

no loop, only builtins.

Run with php -r '<code>' <parameters>.


问:
Find the Infinity Words!
(Note: This is a spin-off of my previous challenge Find the Swirling Words!)

Definition of Infinity Word:

If you connect with curves all the characters of an Infinity Word on the alphabet (A-Z) you obtain the infinity symbol ∞ like in the diagrams below.

All the even connection must be down, all the odd connections must be up.

You can ignore upper/lowercase or consider/convert all to upper case or all to lower case.

The input words are only characters in the alphabet range of A-Z, no spaces, no punctuation, or symbols.

Each word must be exactly 5 characters. Words > 5 or < 5 are not valid.

If a word has double consecutive characters, the word is not valid, like "FLOOD" or "QUEEN".

All the Infinity Words start and end with the same character.

Here there are some examples:

Task:

Write a full program or function that will take a word from standard input and will output if is an Infinity Word or not. The output can be true/false, 1/0, 1/Null, etc.

Test cases:

```<code>Infinity Words:
ALPHA, EAGLE, HARSH, NINON, PINUP, RULER, THEFT, WIDOW

NOT Infinity Words:
CUBIC, ERASE, FLUFF, LABEL, MODEM, RADAR, RIVER, SWISS, TRUST,
KNEES, QUEEN, GROOVE, ONLY, CHARACTER, OFF, IT, ORTHO
</code>```

Rules:

Shortest code wins.

Optional Task:

Find, as a list, as many Infinity Words as you can in an English dictionary. You can take for example as reference the complete list of English words here.

答:
Java 8, <s>231</s> <s>193</s> <s>185</s> <s>122</s> <s>103</s> 78 bytes

```<code>s->s.length==5&&(s[1]-s[0])*(s[3]-s[2])<0&(s[2]-s[1])*(s[4]-s[3])<0&s[4]==s[0]
</code>```

Try it here.

-38 bytes thanks to @dpa97 for reminding me to use char[] instead of String.

-63 bytes thanks to @KarlNapf's derived formula.

-25 bytes by converting it from Java 7 to Java 8 (and now returning a boolean instead of integer).

193 bytes answer:

```<code>int c(char[]s){if(s.length!=5)return 0;int a=s[0],b=s[1],c=s[2],d=s[3],e=s[4],z=b-a,y=c-b,x=d-c,w=e-d;return e!=a?0:(z>0&y>0&x<0&w<0)|(z<0&y>0&x>0&w<0)|(z>0&y<0&x<0&w>0)|(z<0&y<0&x>0&w>0)?1:0;}
</code>```

Explanation:

If the length of the string isn't 5, we return false

If the first character doesn't equal the last character, we return false

Then we check the four valid cases one by one (let's indicate the five characters as 1 through 5), and return true if it complies to any of them (and false otherwise):

If the five characters are distributed like: 1<2<3>4>5 (i.e. ALPHA)

If the five characters are distributed like: 1>2<3<4>5 (i.e. EAGLE, HARSH, NINON, PINUP)

If the five characters are distributed like: 1<2>3>4<5 (i.e. RULER)

If the five characters are distributed like: 1>2>3<4<5 (i.e. THEFT, WIDOW)

These four rules can be simplified to 1*3<0 and 2*4<0 (thanks to @KarlNapf's Python 2 answer).

Title: Find the Infinity Words!

Body:
Java 8, <s>231</s> <s>193</s> <s>185</s> <s>122</s> <s>103</s> 78 bytes

s->s.length==5&&(s[1]-s[0])*(s[3]-s[2])<0&(s[2]-s[1])*(s[4]-s[3])<0&s[4]==s[0]

<a href="https://tio.run/##fVBNT9tAEL3nV4x8QDY0Fh/tBepKi7PBVh079QdRFeWwOBswmHXk3VAhlN8eZoyRKAIu@2b2aebNe7fiQQybtVS3y7tdWQutYSIq9TQAqJSR7UqUEmJqAa6appZCQWmXN6KdL0A7Z0hsB/hoI0xVQgwKPNjp4S/t1lJdmxvP@7G3Z@v50WKo54cLZx/rE6qPF87PQ2KOqTt6Yb5TfdIx1HgezezOSGG9uapRoRd6aKol3OOldmbaSl3jNcJ5OXPVtP0n6E1ZSrnEMpfa@EJLOAUl/8Hr0JPFomnArG8WZxcRRwxYmgWIcRgnMeI0jIspYlpEPEXMAz7OEWfhKJlZ214TIHvURt67zca4a9xtamV/oH4A1ilYCMotP@Bd0/gYLWtb8Wg7ThcvBfyJQM@/MbwSVf2VW784D31ym7KM3I6jYjxGjNg5jxAnyYhPyC0bMXKbhped62wWZhm5T4uM3P@OOaf@T8E5pXSRJsklLUzi6C@CjzEyP@9mk04hSfMg6XOkya@je@/jv9zekZ@Hth1sd88" rel="noreferrer">Try it here.

-38 bytes thanks to @dpa97 for reminding me to use char[] instead of String.

-63 bytes thanks to @KarlNapf's derived formula.

-25 bytes by converting it from Java 7 to Java 8 (and now returning a boolean instead of integer).

193 bytes answer:

int c(char[]s){if(s.length!=5)return 0;int a=s[0],b=s[1],c=s[2],d=s[3],e=s[4],z=b-a,y=c-b,x=d-c,w=e-d;return e!=a?0:(z>0&y>0&x<0&w<0)|(z<0&y>0&x>0&w<0)|(z>0&y<0&x<0&w>0)|(z<0&y<0&x>0&w>0)?1:0;}

Explanation:

If the length of the string isn't 5, we return false

If the first character doesn't equal the last character, we return false

Then we check the four valid cases one by one (let's indicate the five characters as 1 through 5), and return true if it complies to any of them (and false otherwise):

If the five characters are distributed like: 1<2<3>4>5 (i.e. ALPHA)

If the five characters are distributed like: 1>2<3<4>5 (i.e. EAGLE, HARSH, NINON, PINUP)

If the five characters are distributed like: 1<2>3>4<5 (i.e. RULER)

If the five characters are distributed like: 1>2>3<4<5 (i.e. THEFT, WIDOW)

These four rules can be simplified to 1*3<0 and 2*4<0 (thanks to @KarlNapf's Python 2 answer).


Title: Letter-replacement challenge

Body:
The idea is simple. You've to create a "visualised" letter-replacement, by providing 3 strings (input can be comma separated, separate inputs, or as an array). The first segment is the word you want to correct, and the second segment is the letters you want to replace, and the third segment is the replacement for the letters in segment 2.

For example:

```<code>|    | Input                       | Starting Word | Output      |
|----|-----------------------------|---------------|-------------|
| #1 | Hello world -wo -ld +Ea +th | Hello world   | Hello Earth |
| #2 | Hello World -wo -ld +Ea +th | Hello World   | Hello Worth |
| #3 | Hello -llo +y               | Hello         | Hey         |
| #4 | Red -R -d +Gr +en           | Red           | Green       |
| #5 | mississippi -is -i +lz +p   | mississippi   | mlzslzspppp |
| #6 | Football -o -a +a +i        | Football      | Fiitbill    |
| #7 | mississippi -is -i +iz +p   | mississippi   | mpzspzspppp |
</code>```

Explanation

The replacements are to be done step-by-step with their respective pair. Here's an illustration with an input of mississippi -is -i +iz +p to give the output mpzspzsppp (see example #7 above)

```<code>| Step  | Input                         | Output        |
|------ |---------------------------    |-------------  |
| #1    | mississippi -is -i +iz +p     |               |
| #2    | mississippi -is +iz           | mizsizsippi   |
| #3    | mizsizsippi -i +p             | mpzspzspppp   |
</code>```

Rules

Inputs are always in this order <starting_string> <list_of_letters_to_replace> <replacement_letters>.

Letters to replace and replacement groups will never be mixed (ie: there will never be -a +i -e +o).

Letters to replace are always prefixed with - and replacement letters are always prefixed with +. (The prefix is mandatory)

There may be more than one set of letters to replace, so you'd need to look at the prefix.

Assume the amount of letter groups to replace and the amount of replacement letter groups are always equal (ie: there will never be -a -e +i)

Replacements are case-sensitive (see example #1 and #2).

Replacements are done in the order they were given in the input.

Letter replacements can be replaced with other replacements. See example #6.

The first segment (starting word) will never include - or + characters.

This is code-golf so shortest bytes win.

Leaderboards

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

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>```

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
GNU sed 86 Bytes

Includes +1 for -r

:;s,^([^-]*)(\w+)([^-]*-)\2( [^+]*\+)(\w*),\1\5\3\2\4\5,
t;s,-[^-+]*,,;s,\+[^-+]*,,;t

Try it online!

Example:

$ echo 'Hello world -wo -ld +Ea +th'|sed -rf replace.sed
Hello Earth


答:
Python 2, 42 bytes

def f(a,b):
 if b:f([a],b-1)
 else:print a
```

Recursive function

Title: Nest a string inside an array n times

Body:
Python 2, 42 bytes

def f(a,b):
 if b:f([a],b-1)
 else:print a

Recursive function


答:
Postscript, 24 bytes (11 bytes in binary encoding)

```<code>{{1 array astore}repeat}
</code>```

Takes arguments on the stack, n at top-of-stack and s under it

The binary encoding is

```<code>{{1\x92\x09\x92\x0b}\x92\x83}
</code>```

Title: Nest a string inside an array n times

Body:
Postscript, 24 bytes (11 bytes in binary encoding)

{{1 array astore}repeat}

Takes arguments on the stack, n at top-of-stack and s under it

The binary encoding is

{{1\x92\x09\x92\x0b}\x92\x83}


答:
Ruby, 24 bytes

```<code>f=->*s,n{s[n]||f[s,n-1]}
</code>```

Called the same as in manatwork's answer, but a weirder implementation. *s wraps the input (a possibly-nested string) in an array. Then if n is zero, s[n] returns the first element of s, turning the function into a no-op. Otherwise, it returns nil since s will only ever have one element, so we pass through to the recursive call.

Title: Nest a string inside an array n times

Body:
Ruby, 24 bytes

f=->*s,n{s[n]||f[s,n-1]}

Called the same as in manatwork's answer, but a weirder implementation. *s wraps the input (a possibly-nested string) in an array. Then if n is zero, s[n] returns the first element of s, turning the function into a no-op. Otherwise, it returns nil since s will only ever have one element, so we pass through to the recursive call.


问:
Finding prime numbers without using "prime characters"
Your task, if you choose to accept it, is to write a program/function that accepts an integer \$N\$ as input. The program/function should output/return a list of the first \$N\$ prime numbers. But here's the catch: you are not allowed to use prime characters in your code. A prime character is a character whose Unicode code point is a prime number. In the printable ASCII range, these are:

```<code>%)+/5;=CGIOSYaegkmq
</code>```

But the rule also applies to non-ASCII characters if your code uses those.

A valid input is an integer \$N\$ where \$0 < N \le T\$, where you can choose \$T\$, but it has to be greater than or equal to \$10000\$. \$T\$ does not have to be finite.

For invalid inputs (non-integers, integers out of range), throw an exception or output/return nothing/null.

An integer with leading/trailing whitespace as input is considered invalid.

An integer with a + as sign character as input is considered invalid.

An integer with leading zeros as input is considered valid.

If your language allows you to pass an already-parsed integer as input, the above parsing rules (except the range one) don't apply, because the int is already parsed.

The input is always base-10.

Use of built-in prime generators and primality testers (this includes prime factorization functions) is not allowed.

The source restriction is imposed on Unicode characters, but the byte counting for the score can be in another encoding if you wish.

The output can contain a single trailing newline, but this is not required.

If you output/return the prime number list as a string, then every prime number must be delimited by one or multiple non-digit char(s). You can choose which delimiter you use.

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

Stack Snippet to verify your code

You can use the below Stack Snippet to verify that your code does not contain prime chars:

var primes=[],max=10000;for(var i=2;i<=max;i++){primes.push(i);}for(var N=2;N<Math.sqrt(max);N++){if(primes.indexOf(N)===-1){continue;}primes=primes.filter(function (x){return x===N||x%N!==0;});}function setText(elem,text){var z=('innerText' in elem)? 'innerText' : 'textContent';elem[z]=text;}function verify(inputCode,resultSpan){var invalidChars=[];var success=true;for(var i=0;i<inputCode.length;i++){var cc = inputCode.charCodeAt(i);if (cc>max){setText(resultSpan,"Uh oh! The char code was bigger than the max. prime number calculated by the snippet.");success = false;break;}if (primes.indexOf(cc)!==-1){invalidChars.push(inputCode[i]);}}if (invalidChars.length===0&&success){setText(resultSpan, "Valid code!");}else if(success) {  var uniqueInvalidChars = invalidChars.filter(function (x, i, self){return self.indexOf(x)===i;});setText(resultSpan, "Invalid code! Invalid chars: " + uniqueInvalidChars.join(""));    }}document.getElementById("verifyBtn").onclick=function(e){e=e||window.event;e.preventDefault();var code=document.getElementById("codeTxt").value;verify(code,document.getElementById("result"));};```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Enter your code snippet here:<br /><textarea id="codeTxt" rows="5" cols="70"></textarea><br /><button id="verifyBtn">Verify</button><br /><span id="result"></span></code>```

答:
GNU APL, <s>75 68 67 65 59 56</s> 55 characters

⎕IO must be 1.

```<code>∇z←p n
z←2,j←3
j←j--2
→2×⍳∨⌿1>z|j
z←z,j
→2×⍳n>⍴z
z←n↑z∇
</code>```

I came back on this months later realizing that I had an extra space!

ContentLicense: CC BY-SA 4.0

Body:
GNU APL, <s>75 68 67 65 59 56</s> 55 characters

⎕IO must be 1.

∇z←p n
z←2,j←3
j←j--2
→2×⍳∨⌿1>z|j
z←z,j
→2×⍳n>⍴z
z←n↑z∇

I came back on this months later realizing that I had an extra space!


答:
V, 6 bytes

```<code>Àñys$]
</code>```

Try it online!

Explanation:

```<code>À      "Arg1 times
 ñ     "repeat:
  ys$  "surround this line
     ] "with square brackets
</code>```

Title: Nest a string inside an array n times

Body:
V, 6 bytes

Àñys$]

Try it online!

Explanation:

À      "Arg1 times
 ñ     "repeat:
  ys$  "surround this line
     ] "with square brackets


答:
Haskell, <s>85</s> 78 bytes

```<code>import Data.Lists
g=map tail.words
a#b=foldl(flip$uncurry replace)a.zip(g b).g
</code>```

Usage example: ("mississippi" # "-is -i") "+lz +p" -> "mlzslzspppp".

How it works:

```<code>g=map tail.words              -- helper function that splits a string into a
                              -- list of words (at spaces) and drops the first
                              -- char of each word

                zip(g b).g    -- make pairs of strings to be replaced and its
                              -- replacement
foldl(flip$uncurry replace)a  -- execute each replacement, starting with the
                              -- original string
                              -- -> "flip" flips the arguments of "uncurry replace"
                              --           i.e. string before pair of replacements
                              -- "uncurry" turns a function that expects two
                              --           lists into one that expects a list of pairs
</code>```

Edit: @BlackCap found 6 bytes to save and I myself another one.

Title: Letter-replacement challenge

Body:
Haskell, <s>85</s> 78 bytes

import Data.Lists
g=map tail.words
a#b=foldl(flip$uncurry replace)a.zip(g b).g

Usage example: ("mississippi" # "-is -i") "+lz +p" -> "mlzslzspppp".

How it works:

g=map tail.words              -- helper function that splits a string into a
                              -- list of words (at spaces) and drops the first
                              -- char of each word

                zip(g b).g    -- make pairs of strings to be replaced and its
                              -- replacement
foldl(flip$uncurry replace)a  -- execute each replacement, starting with the
                              -- original string
                              -- -> "flip" flips the arguments of "uncurry replace"
                              --           i.e. string before pair of replacements
                              -- "uncurry" turns a function that expects two
                              --           lists into one that expects a list of pairs

Edit: @BlackCap found 6 bytes to save and I myself another one.


答:
JavaScript (ES6), <s>91</s> <s>89</s> 87 bytes

Saved 2 bytes thanks to Ismael Miguel

```<code>s=>(k=0,[...s].reduce((p,c,i)=>(k+=p>c?1<<i:0/(p<c),c)),k?!(k%3)&&!s[5]&&s[0]==s[4]:!1)
</code>```

How it works

We build a 4-bit bitmask k representing the 4 transitions between the 5 characters of the string:

```<code>k += p > c ? 1<<i : 0 / (p < c)
</code>```

if the previous character is higher than the next one, the bit is set

if the previous character is lower then the next one, the bit is not set

if the previous character is identical to the next one, the whole bitmask is forced to NaN so that the word is rejected (to comply with rule #6)

The valid bitmasks are the ones that have exactly two consecutive 1 transitions (the first and the last bits being considered as consecutive as well):

```<code>Binary | Decimal
-------+--------
0011   | 3
0110   | 6
1100   | 12
1001   | 9
</code>```

In other words, these are the combinations which are:

k? : greater than 0

!(k%3) : congruent to 0 modulo 3

lower than 15

The other conditions are:

!s[5] : there's no more than 5 characters

s[0]==s[4] : the 1st and the 5th characters are identical

NB: We don't explicitly check k != 15 because any word following such a pattern will be rejected by this last condition.

Test cases

let f =

s=>(k=0,[...s].reduce((p,c,i)=>(k+=p>c?1<<i:0/(p<c),c)),k?!(k%3)&&!s[5]&&s[0]==s[4]:!1)

console.log("Testing truthy words...");
console.log(f("ALPHA"));
console.log(f("EAGLE"));
console.log(f("HARSH"));
console.log(f("NINON"));
console.log(f("PINUP"));
console.log(f("RULER"));
console.log(f("THEFT"));
console.log(f("WIDOW"));

console.log("Testing falsy words...");
console.log(f("CUBIC"));
console.log(f("ERASE"));
console.log(f("FLUFF"));
console.log(f("LABEL"));
console.log(f("MODEM"));
console.log(f("RADAR"));
console.log(f("RIVER"));
console.log(f("SWISS"));
console.log(f("TRUST"));
console.log(f("KNEES"));
console.log(f("QUEEN"));
console.log(f("ORTHO"));
console.log(f("GROOVE"));
console.log(f("ONLY"));
console.log(f("CHARACTER"));
console.log(f("OFF"));
console.log(f("IT"));
console.log(f("ORTHO"));```
</div>
</div>
</p>

<h3>Initial version</h3>

<p>For the record, my initial version was 63 bytes. It's passing all test cases successfully but fails to detect consecutive identical characters.</p>

```([a,b,c,d,e,f])=>!f&&a==e&&!(((a>b)+2*(b>c)+4*(c>d)+8*(d>e))%3)
```

<p>Below is a 53-byte version suggested by Neil in the comments, which works (and fails) equally well:</p>

```([a,b,c,d,e,f])=>!f&&a==e&&!((a>b)-(b>c)+(c>d)-(d>e))
```

Edit: See Neil's answer for the fixed/completed version of the above code.

Title: Find the Infinity Words!

Body:
(Note: This is a spin-off of my previous challenge Find the Swirling Words!)

Definition of Infinity Word:

If you connect with curves all the characters of an Infinity Word on the alphabet (A-Z) you obtain the infinity symbol ∞ like in the diagrams below.

All the even connection must be down, all the odd connections must be up.

You can ignore upper/lowercase or consider/convert all to upper case or all to lower case.

The input words are only characters in the alphabet range of A-Z, no spaces, no punctuation, or symbols.

Each word must be exactly 5 characters. Words > 5 or < 5 are not valid.

If a word has double consecutive characters, the word is not valid, like "FLOOD" or "QUEEN".

All the Infinity Words start and end with the same character.

Here there are some examples:

Task:

Write a full program or function that will take a word from standard input and will output if is an Infinity Word or not. The output can be true/false, 1/0, 1/Null, etc.

Test cases:

```<code>Infinity Words:
ALPHA, EAGLE, HARSH, NINON, PINUP, RULER, THEFT, WIDOW

NOT Infinity Words:
CUBIC, ERASE, FLUFF, LABEL, MODEM, RADAR, RIVER, SWISS, TRUST,
KNEES, QUEEN, GROOVE, ONLY, CHARACTER, OFF, IT, ORTHO
</code>```

Rules:

Shortest code wins.

Optional Task:

Find, as a list, as many Infinity Words as you can in an English dictionary. You can take for example as reference the complete list of English words here.

Body:
JavaScript (ES6), <s>91</s> <s>89</s> 87 bytes

Saved 2 bytes thanks to Ismael Miguel

s=>(k=0,[...s].reduce((p,c,i)=>(k+=p>c?1<<i:0/(p<c),c)),k?!(k%3)&&!s[5]&&s[0]==s[4]:!1)

How it works

We build a 4-bit bitmask k representing the 4 transitions between the 5 characters of the string:

k += p > c ? 1<<i : 0 / (p < c)

if the previous character is higher than the next one, the bit is set

if the previous character is lower then the next one, the bit is not set

if the previous character is identical to the next one, the whole bitmask is forced to NaN so that the word is rejected (to comply with rule #6)

The valid bitmasks are the ones that have exactly two consecutive 1 transitions (the first and the last bits being considered as consecutive as well):

Binary | Decimal
-------+--------
0011   | 3
0110   | 6
1100   | 12
1001   | 9

In other words, these are the combinations which are:

k? : greater than 0

!(k%3) : congruent to 0 modulo 3

lower than 15

The other conditions are:

!s[5] : there's no more than 5 characters

s[0]==s[4] : the 1st and the 5th characters are identical

NB: We don't explicitly check k != 15 because any word following such a pattern will be rejected by this last condition.

Test cases

let f =

s=>(k=0,[...s].reduce((p,c,i)=>(k+=p>c?1<<i:0/(p<c),c)),k?!(k%3)&&!s[5]&&s[0]==s[4]:!1)

console.log("Testing truthy words...");
console.log(f("ALPHA"));
console.log(f("EAGLE"));
console.log(f("HARSH"));
console.log(f("NINON"));
console.log(f("PINUP"));
console.log(f("RULER"));
console.log(f("THEFT"));
console.log(f("WIDOW"));

console.log("Testing falsy words...");
console.log(f("CUBIC"));
console.log(f("ERASE"));
console.log(f("FLUFF"));
console.log(f("LABEL"));
console.log(f("MODEM"));
console.log(f("RADAR"));
console.log(f("RIVER"));
console.log(f("SWISS"));
console.log(f("TRUST"));
console.log(f("KNEES"));
console.log(f("QUEEN"));
console.log(f("ORTHO"));
console.log(f("GROOVE"));
console.log(f("ONLY"));
console.log(f("CHARACTER"));
console.log(f("OFF"));
console.log(f("IT"));
console.log(f("ORTHO"));

Initial version

For the record, my initial version was 63 bytes. It's passing all test cases successfully but fails to detect consecutive identical characters.

([a,b,c,d,e,f])=>!f&&a==e&&!(((a>b)+2*(b>c)+4*(c>d)+8*(d>e))%3)

Below is a 53-byte version suggested by Neil in the comments, which works (and fails) equally well:

([a,b,c,d,e,f])=>!f&&a==e&&!((a>b)-(b>c)+(c>d)-(d>e))

Edit: See Neil's answer for the fixed/completed version of the above code.


问:
List of first n prime numbers most efficiently and in shortest code
Rules are simple:

First n primes (not primes below n), should be printed to standard output separated by newlines (primes should be generated within the code)

primes cannot be generated by an inbuilt function or through a library, i.e. use of a inbuilt or library function such as, prime = get_nth_prime(n), is_a_prime(number), or factorlist = list_all_factors(number) won't be very creative.

Scoring - Say, we define Score = f([number of chars in the code]), O(f(n)) being the complexity of your algorithm where n is the number of primes it finds. So for example, if you have a 300 char code with O(n^2) complexity, score is 300^2 = 90000, for 300 chars with O(n*ln(n)), score becomes 300*5.7 = 1711.13 (let's assume all logs to be natural logs for simplicity)

Use any existing programming language, lowest score wins

Edit: Problem has been changed from finding 'first 1000000 primes' to 'first n primes' because of a confusion about what 'n' in O(f(n)) is, n is the number of primes you find (finding primes is the problem here and so complexity of the problem depends on the number of primes found)

Note: to clarify some confusions on complexity, if 'n' is the number of primes you find and 'N' is the nth prime found, complexity in terms of n is and N are not equivalent i.e. O(f(n)) != O(f(N)) as , f(N) != constant * f(n) and N != constant * n, because we know that nth prime function is not linear, I though since we were finding 'n' primes complexity should be easily expressible in terms of 'n'.

As pointed out by Kibbee, you can visit this site to verify your solutions (here, is the old google docs list)

Please Include these in your solution -

what complexity your program has (include basic analysis if not trivial)

character length of code

the final calculated score

This is my first CodeGolf Question so, if there is a mistake or loophole in above rules please do point them out.

答:
Groovy (50 Bytes) - O(n*sqrt(n)) - Score 353.553390593

```<code>{[1,2]+(1..it).findAll{x->(2..x**0.5).every{x%it}}}
</code>```

Takes in n and outputs all numbers from 1 to n which are prime.

The algorithm I chose only outputs primes n > 2, so adding 1,2 at the beginning is required.

Breakdown

x%it - Implicit truthy if it is not divisible, falsy if it is.

(2..x**0.5).every{...} - For all the values between 2 and sqrt(x) ensure that they are not divisible, for this to return true, must return true for every.

(1..it).findAll{x->...} - For all values between 1 and n, find all that fit the criteria of being non-divisible between 2 and sqrt(n).

{[1,2]+...} - Add 1 and 2, because they are always prime and never covered by algorithm.

Body:
Groovy (50 Bytes) - O(n*sqrt(n)) - Score 353.553390593

{[1,2]+(1..it).findAll{x->(2..x**0.5).every{x%it}}}

Takes in n and outputs all numbers from 1 to n which are prime.

The algorithm I chose only outputs primes n > 2, so adding 1,2 at the beginning is required.

Breakdown

x%it - Implicit truthy if it is not divisible, falsy if it is.

(2..x**0.5).every{...} - For all the values between 2 and sqrt(x) ensure that they are not divisible, for this to return true, must return true for every.

(1..it).findAll{x->...} - For all values between 1 and n, find all that fit the criteria of being non-divisible between 2 and sqrt(n).

{[1,2]+...} - Add 1 and 2, because they are always prime and never covered by algorithm.


答:
Jelly, <s>43 41 40 25 24 23 22 21 14</s> 13 bytes

-7 bytes thanks to fireflame241 (0ị=1ị$->=ṚḢ and use of IIA⁼2,2 to test for the 4 rotations)

-1 Thanks to Kevin Cruijssen (use of previously unavailable nilad Ø2 which yields [2,2])

```<code>=ṚḢȧOIṠIIA⁼Ø2
</code>```

TryItOnline

Or all test cases (plus "RULES")

How?

An infinity word has:

the same first and last letter;

length 5;

no equal letters next to each other;

sum of its four alphabet deltas equal to zero;

sum of its four alphabet deltas signs equal to zero;

two positive alphabet deltas or two negative alphabet deltas in a row.

All but (1) and (equivalently) (4) may be boiled down to a condition that the alphabet delta signs are some rotation of [1,1,-1,-1] (where the sign of 0 is 0)

fireflame241 noted that this is then equivalent to the deltas of the deltas of the alphabet delta signs being in [[2,2],[2,-2],[-2,2],[-2,-2]] which may be tested by the absolute values being equal to [2,2]!

How?

```<code>=ṚḢȧOIṠIIA⁼Ø2 - Main link: word
 Ṛ            - reverse word
=             - equals? (vectorises)
  Ḣ           - head (is the first character equal to the last?)
   ȧ          - and
    O         - cast word to ordinals
     I        - increments - the alphabet deltas (or just [] if 1st != last)
      Ṡ       - sign (vectorises)
       I      - increments - deltas of those signs
        I     - increments - deltas of those
         A    - absolute value (vectorises)
           Ø2 - literal [2,2]
          ⁼   - equals? (non-vectorising version)
</code>```

Title: Find the Infinity Words!

Body:
Jelly, <s>43 41 40 25 24 23 22 21 14</s> 13 bytes

-7 bytes thanks to fireflame241 (0ị=1ị$->=ṚḢ and use of IIA⁼2,2 to test for the 4 rotations)

-1 Thanks to Kevin Cruijssen (use of previously unavailable nilad Ø2 which yields [2,2])

=ṚḢȧOIṠIIA⁼Ø2

TryItOnline

Or all test cases (plus "RULES")

How?

An infinity word has:

the same first and last letter;

length 5;

no equal letters next to each other;

sum of its four alphabet deltas equal to zero;

sum of its four alphabet deltas signs equal to zero;

two positive alphabet deltas or two negative alphabet deltas in a row.

All but (1) and (equivalently) (4) may be boiled down to a condition that the alphabet delta signs are some rotation of [1,1,-1,-1] (where the sign of 0 is 0)

fireflame241 noted that this is then equivalent to the deltas of the deltas of the alphabet delta signs being in [[2,2],[2,-2],[-2,2],[-2,-2]] which may be tested by the absolute values being equal to [2,2]!

How?

=ṚḢȧOIṠIIA⁼Ø2 - Main link: word
 Ṛ            - reverse word
=             - equals? (vectorises)
  Ḣ           - head (is the first character equal to the last?)
   ȧ          - and
    O         - cast word to ordinals
     I        - increments - the alphabet deltas (or just [] if 1st != last)
      Ṡ       - sign (vectorises)
       I      - increments - deltas of those signs
        I     - increments - deltas of those
         A    - absolute value (vectorises)
           Ø2 - literal [2,2]
          ⁼   - equals? (non-vectorising version)