11 KiB
title | id | localeTitle | challengeType |
---|---|---|---|
Execute a Markov algorithm | 59e09e6d412c5939baa02d16 | 59e09e6d412c5939baa02d16 | 5 |
Description
Crear un intérprete para un algoritmo de Markov .
Las reglas tienen la sintaxis:
:: = (( | ) +) *
:: = # { }
:: = -> [.]
:: = ( | ) [ ]
Hay una regla por línea.
Si hay un . (periodo) presente antes del , entonces esta es una regla de terminación, en cuyo caso el intérprete debe detener la ejecución.
Un conjunto de reglas consiste en una secuencia de reglas, con comentarios opcionales.
Reglas
Utilice las siguientes pruebas en las entradas:
Reglas 1:Este archivo de reglas se extrae de Wikipedia: http://en.wikipedia.org/wiki/Markov_AlgorithmA -> apple B -> bag S -> shop T -> the the shop -> my brother a nunca usado -> regla de terminación
Texto de ejemplo de:
I bought a B of As from T S.
Debe generar la salida:
I bought a bag of apples from my brother.
Una prueba de la regla de terminación.
Modificado ligeramente de las reglas de WikipediaA -> manzana B -> bolsa S -> .shop T -> el la tienda -> mi hermano una regla nunca utilizada -> .terminating
Texto de ejemplo de:
I bought a B of As from T S.
Debe generar:
I bought a bag of apples from T shop.
Esto prueba el orden de sustitución correcto y puede interceptar rutinas de reemplazo basadas en expresiones regulares simples si no se escapan los caracteres de expresiones regulares especiales.
BNF Reglas de prueba de sintaxisA -> apple WWWW -> con Bgage -> ->. * B -> bolsa ->. * -> money W -> WW S -> .shop T -> the la tienda -> mi hermano a nunca usado -> .terminando la regla
Texto de ejemplo de:
I bought a B of As W my Bgage from T S.
Debe generar:
I bought a bag of apples with my money from T shop.
Esto prueba el orden correcto de escaneo de las reglas y puede interceptar las rutinas de reemplazo que escanean en el orden incorrecto. Implementa un motor general de multiplicación unaria. (Tenga en cuenta que la expresión de entrada se debe colocar dentro de los guiones bajos en esta implementación).
## Unary Multiplication Engine, para probar las implementaciones del algoritmo de Markov ## Por Donal Fellows. Motor de suma unitaria_ + 1 -> _1 + 1 + 1 -> 11+ Pase para convertir de la división de la multiplicación en suma ordinaria1! ->! 1 ,! ->! + _! -> _ Multiplicación unaria duplicando el lado izquierdo, lado derecho veces1 * 1 -> x, @ y 1x -> xX X, -> 1,1 X1 -> 1X _x -> _X , x -> , X y1 -> 1y y_ -> _ Siguiente fase de aplicación1 @ 1 -> x, @ y 1 @ _ -> @_ , @ _ ->! _ ++ -> + Limpieza de terminación para el agregado_1 -> 1 1 + _ -> 1 _ + _ ->
Texto de ejemplo de:
_1111*11111_
debe generar la salida:
11111111111111111111
Una simple máquina de Turing ,
Implementando un castor ocupado de tres estados.
La cinta consta de 0s y 1s, los estados son A, B, C y H (para Halt), y la posición del encabezado se indica escribiendo la letra del estado antes del carácter donde está el encabezado.
Todas las partes de la cinta inicial en la que opera la máquina deben incluirse en la entrada.
Además de demostrar que el algoritmo de Markov está completo en Turing, también me hizo detectar un error en la implementación de C ++ que no se detectó en los primeros cuatro conjuntos de reglas.
Máquina de Turing: castor ocupado de tres estados # estado A, símbolo 0 => escribir 1, mover a la derecha, nuevo estado BA0 -> 1B estado A, símbolo 1 => escribir 1, mover a la izquierda, nuevo estado C0A1 -> C01 1A1 -> C11 estado B, símbolo 0 => escritura 1, mover a la izquierda, nuevo estado A0B0 -> A01 1B0 -> A11 estado B, símbolo 1 => escribir 1, mover a la derecha, nuevo estado BB1 -> 1B estado C, símbolo 0 => escribir 1, mover a la izquierda, nuevo estado B0C0 -> B01 1C0 -> B11 estado C, símbolo 1 => escribir 1, mover a la izquierda, halt0C1 -> H01 1C1 -> H11
Este conjunto de reglas debe girar
000000A000000
dentro
00011H1111000
Instructions
Tests
tests:
- text: <code>markov</code> es una función.
testString: 'assert(typeof markov === "function", "<code>markov</code> is a function.");'
- text: ' <code>markov(["A -> apple","B -> bag","S -> shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S.")</code> debería devolver" Compré una bolsa de manzanas de mi hermano ".
testString: 'assert.deepEqual(markov(rules[0],tests[0]),outputs[0],"<code>markov(["A -> apple","B -> bag","S -> shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S.")</code> should return "I bought a bag of apples from my brother.".");'
- text: ' <code>markov(["A -> apple","B -> bag","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S.")</code> debería devolver" Compré una bolsa de manzanas en la tienda de T ".
testString: 'assert.deepEqual(markov(rules[1],tests[1]),outputs[1],"<code>markov(["A -> apple","B -> bag","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S.")</code> should return "I bought a bag of apples from T shop.".");'
- text: ' <code>markov(["A -> apple","WWWW -> with","Bgage -> ->.*","B -> bag","->.* -> money","W -> WW","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As W my Bgage from T S.")</code> debería devolver" Compré una bolsa de manzanas con mi dinero de la tienda ". '
testString: 'assert.deepEqual(markov(rules[2],tests[2]),outputs[2],"<code>markov(["A -> apple","WWWW -> with","Bgage -> ->.*","B -> bag","->.* -> money","W -> WW","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As W my Bgage from T S.")</code> should return "I bought a bag of apples with my money from T shop.".");'
- text: ' <code>markov(["_+1 -> _1+","1+1 -> 11+","1! -> !1",",! -> !+","_! -> _","1*1 -> x,@y","1x -> xX","X, -> 1,1","X1 -> 1X","_x -> _X",",x -> ,X","y1 -> 1y","y_ -> _","1@1 -> x,@y","1@_ -> @_",",@_ -> !_","++ -> +","_1 -> 1","1+_ -> 1","_+_ -> "],"_1111*11111_")</code> debe devolver" 11111111111111111111 ". '
testString: 'assert.deepEqual(markov(rules[3],tests[3]),outputs[3],"<code>markov(["_+1 -> _1+","1+1 -> 11+","1! -> !1",",! -> !+","_! -> _","1*1 -> x,@y","1x -> xX","X, -> 1,1","X1 -> 1X","_x -> _X",",x -> ,X","y1 -> 1y","y_ -> _","1@1 -> x,@y","1@_ -> @_",",@_ -> !_","++ -> +","_1 -> 1","1+_ -> 1","_+_ -> "],"_1111*11111_")</code> should return "11111111111111111111".");'
- text: ' <code>markov(["A0 -> 1B","0A1 -> C01","1A1 -> C11","0B0 -> A01","1B0 -> A11","B1 -> 1B","0C0 -> B01","1C0 -> B11","0C1 -> H01","1C1 -> H11"],"")</code> debe devolver" 00011H1111000 ". '
testString: 'assert.deepEqual(markov(rules[4],tests[4]),outputs[4],"<code>markov(["A0 -> 1B","0A1 -> C01","1A1 -> C11","0B0 -> A01","1B0 -> A11","B1 -> 1B","0C0 -> B01","1C0 -> B11","0C1 -> H01","1C1 -> H11"],"")</code> should return "00011H1111000".");'
Challenge Seed
function markov (rules,test) {
// Good luck!
}
Solution
function markov(rules,test) {
let pattern = new RegExp("^([^#]*?)\\s+->\\s+(\\.?)(.*)");
let origTest = test;
let captures = [];
rules.forEach(function(rule){
let m = pattern.exec(rule);
for (let j = 0; j < m.length; j++)
m[j] = m[j + 1];
captures.push(m);
});
test = origTest;
let copy = test;
for (let j = 0; j < captures.length; j++) {
let c = captures[j];
test = test.replace(c[0], c[2]);
if (c[1]==".")
break;
if (test!=copy) {
j = -1;
copy = test;
}
}
return test;
}
// tail:
let rules=[["A -> apple","B -> bag","S -> shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],
["A -> apple","B -> bag","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],
["A -> apple","WWWW -> with","Bgage -> ->.*","B -> bag","->.* -> money","W -> WW","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],
["_+1 -> _1+","1+1 -> 11+","1! -> !1",",! -> !+","_! -> _","1*1 -> x,@y","1x -> xX","X, -> 1,1","X1 -> 1X","_x -> _X",",x -> ,X","y1 -> 1y","y_ -> _","1@1 -> x,@y","1@_ -> @_",",@_ -> !_","++ -> +","_1 -> 1","1+_ -> 1","_+_ -> "],
["A0 -> 1B","0A1 -> C01","1A1 -> C11","0B0 -> A01","1B0 -> A11","B1 -> 1B","0C0 -> B01","1C0 -> B11","0C1 -> H01","1C1 -> H11"]];
let tests=["I bought a B of As from T S.",
"I bought a B of As from T S.",
"I bought a B of As W my Bgage from T S.",
"_1111*11111_",
"000000A000000"];
let outputs=["I bought a bag of apples from my brother.",
"I bought a bag of apples from T shop.",
"I bought a bag of apples with my money from T shop.",
"11111111111111111111",
"00011H1111000"];