Cops: faire une regex - faire un serpent


40

C'est le fil du flic. Le fil du voleur est ici .


Ecrivez un code qui prend une entrée net crée une "matrice de serpent" n-by-n.

Une matrice de serpent est une matrice qui suit ce modèle:

3-sur-3:

1  2  3
6  5  4
7  8  9

et 4 par 4:

1   2   3   4
8   7   6   5
9   10  11  12
16  15  14  13

Le format de sortie exact est facultatif. Vous pouvez par exemple une sortie [[1 2 3],[6 5 4],[7 8 9]], ou quelque chose de similaire.

Vous devez fournir le nom de la langue et une expression régulière qui correspond parfaitement à votre code. Vous pouvez choisir le niveau de détail de votre expression rationnelle. À la limite, vous pouvez écrire une regex qui correspond à toutes les chaînes possibles, auquel cas il sera très facile de déchiffrer votre code. Vous devez également fournir la sortie pour n=4que les cambrioleurs sachent le format exact que vous avez choisi.

Vous pouvez utiliser l’une des saveurs regex disponibles sur regex101.com ou la saveur Ruby.

  • PCRE (PHP)
  • Javascript
  • Python
  • Golang
  • Rubis

Vous devez spécifier lequel vous utilisez.

Remarques:

  • Vous devez supporter toute taille raisonnable n . Vous pouvez supposer que le type de données ou la mémoire ne sera pas dépassé. Si le type de données par défaut est des entiers signés sur 8 bits, vous pouvez supposer que n<=11s'il s'agit d'entiers non signés sur 8 bits, vous pouvez alors assumer n<=15.
  • Les voleurs doivent correspondre au format de sortie de la soumission, à l'exception des espaces de début / fin et des nouvelles lignes, car cela aurait pu être supprimé par le formatage SE.

Critère gagnant:

Le gagnant sera la soumission non fissurée avec la regex la plus courte, mesurée en nombre de caractères.

Si votre publication est restée ouverte pendant 7 jours, vous pouvez alors publier la solution et marquer votre soumission comme étant sûre.


5
Graine, longueur 1, ..
Kritixi Lithos

1
Puis-je utiliser l'un des langages documentés ici? codegolf.stackexchange.com/questions/61804/…

2
@KritixiLithos Sauf que vous devez publier votre programme d'origine pour plus de sécurité ;-)
ETHproductions

3
@DeepakAgarwal - Écrivez votre code pour générer un serpent, puis fournissez une regex qui lui correspond. La solution du voleur doit être dans la même langue et correspondre à la regex. Une stratégie consiste donc à fournir une expression rationnelle restrictive, pour rendre la tâche du voleur difficile, mais pas trop restrictive pour que vous donniez la solution!

2
Ce méta-consensus autorisant les entrées-sorties unaires pour sed, qui n’a aucun type de données, est-il valide pour ce défi?
Seshoumara

Réponses:


9

05AB1E , fissuré par mbomb007

Si tout va bien amusant à craquer et pas trop évident.

Regex (PCRE):

^\w*[+\-*\/%]*\w*.{0,2}$

Sortie n = 4:

[[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]]

Solution originale

UXFXLNX*+NFR}ˆ

oooooomg - mec c'est dope (compliment, bien sûr)
Tilak Maddy

@ mbomb007: les lettres accentuées ne correspondent pas à \wno. Vous pouvez vous essayer à regex101
Emigna

1
Vous pouvez raccourcir votre regex en changeant .{0,2}de.?.?
Aaron

1
Vous pouvez mettre la -dernière position de la classe char entre crochets ( [+*\/%-]) pour ne pas y échapper.
Dada

@ Dada: Cela fonctionne bien dans PCRE. Je ne suis pas terriblement préoccupé par le raccourcissement actuel, car je suis à peu près certain qu'il sera fissuré. Si cela vous convient, je vais incorporer vos suggestions et celles d'Aarons. Merci :)
Emigna


7

Gelée , longueur 6, fissurée

Regex (PCRE)

^.{9}$

Échantillon de sortie

 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13

3
Cela oblige vraiment à bien
jouer

1
Tous les neuf personnages? Vous vous sentez généreux! : D
AdmBorkBork

1
"Neuf" Combien y avait-il de fonctions dans Jelly?
Matthew Roh

Je suis à 99% certain que le dernier caractère doit être Gde formater correctement la sortie. Je suis sur le point de résoudre le reste du problème, mais je ne vois pas comment renverser tous les autres éléments d'un tableau avec Jelly ...
ETHproductions

@ETHproductions: J'étais presque certain de l'avoir presque résolu et j'ai une méthode pour inverser tous les autres éléments. Mon problème est que je n'arrive pas à comprendre comment tout lier (je n'ai pas essayé le tutoriel). Je m'attendais à le voir résolu maintenant cependant. Peut-être que c'est plus difficile que je ne le pense.
Emigna

6

R, longueur 14 Fissuré par le plannapus

J'espère que j'ai bien compris cette regex. Ce que je veux dire est de 77 caractères à l' exclusion <space>, #, ;et [. Je l'ai testé ici

Regex

^[^ #;\[]{77}$

Exemple de sortie n = 4

1 2 3 4 
8 7 6 5 
9 10 11 12 
16 15 14 13  

Je pensais que cela serait facile, mais j’ai beaucoup de difficulté à obtenir ces chiffres (plutôt qu’un tableau). Bon travail.
BLT

1
@BLT Merci, c'était un problème intéressant d'essayer de rendre difficile.
MickyT

Craqué , mais probablement pas le même code que le vôtre.
Plannapus


6

> <> , longueur 49, fissuré par Aaron

Regex (Javascript)

^.{7}\n.{12}\n\?.{6};[^v^]{27}(\n.{13}:&.{2}){2}$

Exemple de sortie (n = 4)

1 2 3 4 
8 7 6 5 
9 10 11 12 
16 15 14 13 

Le formatage est un peu bizarre, mais vérifier la longueur du nombre aurait été beaucoup plus long. Aurait pu aller un peu trop loin sur la regex, pas sûr!

Edit: De plus, j’ai oublié de mentionner que j’utilise la pile initiale (indicateur -v) pour l’entrée, pas l’entrée fish habituelle. Désolé!

Code d'origine:

<v1*2&:
 >:{:}=?v:1+
?^{r0}v;>&:&[r]{&:&2*+}::&:::&*@+@(
+:}=?v>n" "o&:&{1
0~{oa<^v?)*&::&:}

Aaron est beaucoup plus simple! La complexité de mon code d'origine repose sur l'idée d'utiliser n[r]chaque nième nombre pour retourner ce segment (ligne), puis d'afficher tous les nombres en même temps à la fin.


1
..est plus court que .{2};)
Aaron

Peu importe, fissuré ça ! Évidemment, je n'ai pas trop suivi votre code, mais c'était quand même un défi intéressant. S'il vous plaît partager votre code original! Aussi, si vous le souhaitez, vous pouvez retourner la faveur ;)
Aaron

@Aaron beau travail! aussi ouais je ne suis pas sûr de savoir comment je ne l'ai pas remarqué dans les regex. oh bien :) Je vais voir si je peux craquer le vôtre
torcado

5

Ohm , fissuré

Également mon premier défi Cops and Robbers, alors dites-moi s’il ya des problèmes avec ce modèle (d’autant plus que c’est une langue assez inconnue).

Regex (PCRE)

^\S{6}\W{0,3}\w$

Sortie (n = 4)

[[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]]

1
Si quelque chose, c'est peut-être trop facile. Si vous avez .*dans votre regex, cela pourrait être n'importe quoi. Ainsi, si la langue contient des commentaires, ils peuvent écrire n’importe quel programme suivi d’un commentaire.
mbomb007

@ mbomb007 Bon point.
Nick Clifford


@ Emigna Bien joué!
Nick Clifford

5

PHP, 221 octets ( fissuré )

J'espère que c'est assez difficile.

Regex (PCRE): 16 octets

^[^\s/\#6]{221}$

Pas d'espace, pas de commentaires, pas d'utilisation de base64_decode. S'amuser.

Sortie

  1  2  3  4
  8  7  6  5
  9 10 11 12
 16 15 14 13

Code d'origine

$w=$argv[1];$s="";$r=range(1,$w**2);for($i=0;$i<$w;$i++)if($i%2)array_splice($r,$i*$w,$w,array_reverse(array_slice($r,$i*$w,$w)));foreach(($r)as$v)$s.=str_pad($v,$l=strlen(max($r))+1,"\x20",0);echo(chunk_split($s,$l*$w));

Veuillez noter que les réponses peuvent être utiles base64_decodecar votre expression rationnelle ne l’interdit pas.
CalculatriceFeline

4
@CalculatorFeline: les blocs d'expression régulière 6, ce qui pourrait bloquer base64_decode.
Nneonneo


Oups, j'ai raté ça. Mais alors, peu importe.
CalculatorFeline

5

C # net46 (fissuré)

( http://ideone.com/ works)

Regex PCRE flavour length 58 testé sur regex101

^sta((?![\d%bh\/]|==|if|(\[.*){4}|(i.*){6}).){142}urn....$

Seule la méthode est regexed. La méthode retourne un tableau 2d int [,] (int [4,4]) pour une entrée n = 4. Si imprimé ressemble à ceci:

1 2 3 4 
8 7 6 5 
9 10 11 12 
16 15 14 13 

Ceci est ma première entrée dans quelque chose comme ça, laissez-moi savoir si j'ai fait quelque chose de mal. N'essayant certainement pas de gagner par la longueur de la regex, je suis simplement intéressé de voir comment j'ai réussi à prévenir la fissuration :)

Code d'origine:

static int[,]g(int n){int l,j,k=n-n,c,s;var _=new int[n,n];var d=n!=n;c=k;c++;s=k;for(l=k;l<n;l++){for(j=k;j<n;j++){_[l,d?n-j-c:j]=++s;}d=!d;}return _;}


Bien fait, j'aurais dû essayer de rendre la longueur plus difficile au moins ...
EklipZ

5

QBasic, longueur de regex 10 ( fissuré )

Regex

Devrait fonctionner dans n'importe quelle saveur regex, mais nous l'appellerons saveur Python.

([A-Z]+.)+

REMARQUE: Ma solution utilise QBasic non formaté. après le formatage, le code ne correspond pas à l'expression régulière à cause d'espaces ajoutés. (Mais je peux vous dire que c'est le seul changement qui fait la différence.([A-Z]+ ?. ?)+ Fonctionne toujours sur la version formatée.)

À des fins de test, j'ai utilisé QB64 avec le formatage du code désactivé (sous Options> Disposition du code). Si vous ne souhaitez pas télécharger quelque chose, vous pouvez également exécuter QBasic en ligne sur archive.org (mais vous ne pouvez pas désactiver le formatage).

Échantillon de sortie

 1  2  3  4 
 8  7  6  5 
 9  10  11  12 
 16  15  14  13 

Tous les symboles de la source doivent donc être précédés d'une lettre.
CalculatriceFeline

@CalculatorFeline Une ou plusieurs lettres.
mbomb007

Eh bien, mon exigence est équivalente car \w+\Wpeut être divisée en \w*et \w\W. ( \w*est soit null(trivial) ou \w+(facilement faufilé avec un symbole))
CalculatorFeline

@CalculatorFeline Rien ne dit que le .mot ne peut pas être. Il peut s'agir d'une lettre minuscule ou d'un chiffre. En fait, il pourrait même s'agir d'une lettre majuscule, dans le cas où le dernier caractère du programme en est un.
mbomb007


5

Python 3, 55 bytes (Cracked)

PCRE / Python / Golang flavor.

def [triangles=(1,SNAKE)]{27}:print[]SNAKE(--:>or[]{48}

(Be reminded that Full match is required. Assume ^ and $ when testing.)

Sample output:

[1, 2, 3, 4]
[8, 7, 6, 5]
[9, 10, 11, 12]
[16, 15, 14, 13]

Original solution:

def r(N,S=1,A=1,K=range,E=list):print(E(K(S,S+N))[::A])or(S+N>N*N)or(r(N,S+N,-A,K,E))

Should have trimmed 4 bytes :p


It seems for me that you miss the ) in the second part of the regex
Jörg Hülsermann

@JörgHülsermann no nothing is missing, the regex is correct.
kennytm

1
@JörgHülsermann The extra ( is inside a character class starting after print and ending before {48}. Took me a while to see it too. ;) (For that matter, the earlier pair of parentheses are also inside a character class.)
DLosc

@DLosc Now it is clear . Thank You
Jörg Hülsermann


5

dc, Regex length 12   Cracked by seshoumara!

^[^# !]{59}$

Cette expression régulière est assez simple pour que je ne pense pas que la saveur de la regex importe - elle devrait fonctionner à tous les niveaux. (Notez l'espace après le # dans la regex.)

J'ai testé les quatre versions sur regex101.com (PCRE / PHP, Javascript, Python et Golang), ainsi que la version Ruby sur rubular.com. Le programme dc correspond à la regex dans les cinq versions de regex.


Le programme dc prend son entrée sur stdin et met sa sortie sur stdout.

Exemple de sortie pour l'entrée 4 (il y a un espace de fin à la fin de chaque ligne):

1 2 3 4 
8 7 6 5 
9 10 11 12 
16 15 14 13 

Code original (ajouté après avoir été craqué)

Ceci a été craqué par @seshoumara . Voici mon code prévu:

?sd[AP]s+0[dddld/2%rld%2*1+ldr-*+1+n2CP1+dld%0=+dvld>l]dslx

Explication:

?sd      Input number and store it in register d.
[AP]s+   Macro that prints a newline. The macro is stored in register '+'.
0        Push 0 on the stack, initializing a loop.  (The top of the stack is the index variable.  It will go up to d^2-1.)
[        Start a macro definition.  (The macro will be stored in register l.)
ddd      Push 3 copies of the loop index variable on the stack, so they'll be available later. I'll call this number i.
ld/      Divide the last copy of i by d (integer division); this computes the row of the square that we're in (starting with row 0).
2%       Replace the row number with 0 if the row number is even, with 1 if the row number is odd.
r        Swap the top two items on the stack, so the top item is now the next to last copy of i, and the second item on the stack is the row number mod 2.
ld%      Compute i mod d; this goes from 0 to d-1. It is the column in the square that the next number will be placed in.  (The leftmost column is column 0.)
2*1+     Top of the stack is replaced with 2*(column number)+1.
ldr      Inserts d as the second item on the stack.
-        Computes d-2*(column number)-1.
*        The second item on the stack is the row number mod 2, so multiplying yields 0 if the row number is even, and d-2*(column number)-1 if the row number is odd.
+        Add to the remaining copy of i. The sum is i itself in even-numbered rows, and it's i+d-2*(column number)-1 in odd-numbered rows.

La somme au sommet de la pile est maintenant le prochain nombre que nous voulons imprimer:

  • Il est facile de voir que c'est correct si le numéro de ligne est pair, puisque la somme n'est que i.

  • For odd-numbered rows, notice that i = d*(i/d)+(i%d) = d * (row number) + column number. It follows that the sum i+d-2*(column number)-1 is d * (row number) + column number + d - 2*(column number)- 1 = d * (row number + 1) - column number - 1, which is the number we want to put in the indicated row and column to ensure that we're counting backwards in the odd-numbered rows.

Returning to the explanation now:

n        Print the desired number for the current row and column.
2CP      Print a space.  (2C, which is computed by dc as 20 + 12, is 32, the ASCII code for a space.)
1+       The original copy of i is at the top of the stack; add 1 to it.
dld%0=+  If (the incremented value of) i is a multiple of d, call the macro at register '+', which prints a newline.
dvld>l   If d > sqrt(i) (in other words, if i < d^2), then go back to the top of the loop by calling macro l again.
]dslx    End the macro definition, store the macro in register l, and execute it.

Are the chars # and ` ` omitted so that a shorter solution can't use comments to reach 59 bytes? If so, there's no need since in dc there are so many ways to add commands that don't change anything, for ex. repeating q commands at the end of the script.
seshoumara

@seshoumara It's meant to be a nod in that direction while still keeping the regex short. But you're right, of course. (This is my first cops-and-robbers entry, so I'm not sure how easy it is.)
Mitchell Spector

Cracked!. Getting to slightly more than 59 bytes was easy, but matching your limit or under was more difficult than I expected. As for the regex, the space was ok to omit, my bad, since one needs to print it, so I had to use something else.
seshoumara

@seshoumara Nice job!
Mitchell Spector

@seshoumara By the way, spaces are also useful in dc to separate two successive numerical constants, so prohibiting spaces requires a workaround if you need that functionality. However, printing a space is no big deal, because 32P is shorter than [ ]n anyway.
Mitchell Spector


5

PHP

I hope this will be a fun one! :D

Output (n=4)

[[1,2,3,4],[8,7,6,5],[9,10,11,12],[16,15,14,13]]

Level 1: PCRE (length=17) (Cracked by Jörg Hülsermann)

^<[^'"\d{vV;<$]+$
  • No single or double quotes so... no strings!
  • No digits!
  • No { so... no anonymous functions!
  • No v so... no eval()!
  • No ; so... it must be a single statement!
  • No < so... no Heredoc nor multiple PHP blocks!
  • The big one! No $ so... good luck defining variables! >:D

@JörgHülsermann had an interesting approach, but it's not what I had in mind :). Therefore, I'm introducing a new level of difficulty (I promise I have the code that fits this and I'm not just messing with you):

Level 2: PCRE (length=23) (Cracked by Jörg Hülsermann)

^<[^'"\d{v;<$_~|&A-Z]+$
  • All the restrictions of Level 1
  • New on this level: none of these _~|&A-Z! :)

Have fun!


THE ORIGINAL SOLUTION

So, forbidding the $ meant the variables couldn't be accessed the regular way, but that doesn't mean they can't be used at all! You can still use extract()/compact() to import/export variables into the current scope. :)

$i = 1;
// can be written as
extract(['i' => 1])

echo $i;
// can be written as
echo compact('i')['i'];

However, there's a gotcha: compact('x')['x']++ wouldn't work because variables in PHP are passed by value... with one exception! Objects.

$x = (object) ['i' => 1];
// is
extract(['x' => (object) ['i' => 1]]);

// and
compact('x')['x']->i++;
// works just fine!

The rest is easy.

  • Numbers 0 and 1 are easily generated by converting false and true to int by prepending them with the + sign
  • Use and and or since & and | are forbidden
  • To work around the forbidden quotes, just use undefined constants, which are treated as strings
  • To suppress the notices generated by using undefined constants, just use @
  • The forbidden letter v can be generated by using chr(ord('u') + 1), which translates to @chr(ord(u) + true) using the above workarounds
  • The underscore is similar to the above: chr(ord('a') - 2) which translates to chr(ord(a) - true - true)
  • Calling functions which contain forbidden characters can be done by taking advantage of PHP's callable type, which can be a string containing the name of the function. So, you can concatenate undefined constants and single character strings generated by ord() to build the name of the function and invoke it like this: array_reverse() becomes (a.rray.chr(ord(a)-true-true).re.chr(ord(u)+true).erse)() (array is a language construct, that's why it's split into the undefined constants a and rray)
  • Take advantage of the fact that, when it comes to conditional and loop constructs, the curly brackets are optional if the construct applies just to the immediately following statement. This means you can do stuff like: if ($n = $argv[1] and $i = 0) while ($n > $i++ and do_some and other_stuff or exit)

The logic in human readable code would be:

if (
    $x = (object) [
        'result' => [],
        'i' => 0
    ]

    and

    define('n', $argv[1])

    and

    define('un', '_')

    and

    // create the initial set which we'll loop through
    define('segments', array_chunk(range(1, pow(n, 2)), n))
) while (
    // store each odd segment as-is and increment the "pointer"
    ($x->result[] = @segments[$x->i++])

    and

    // store each even segment reversed and increment the "pointer"
    ($x->result[] = @array_reverse(segments[$x->i++]))

    and

    // check if we need to break out of the loop
    n > $x->i

    or

    // exit and output the result if the above is false
    die(json_encode(
        // if n is odd, the above would have copied a NULL entry 
        // from the segments, so it needs to be filtered out
        array_filter($x->result)
    ))
)

And the unfriendly version that matches the regex:

<?php if (@extract([x=>(object)[s=>[],i=>+false]])and@define(n,compact(arg.chr(ord(u)+true))[arg.chr(ord(u)+true)][+true]?:+true)and@define(un,chr(ord(a)-true-true))and@define(s,(a.rray.un.chunk)(range(+true,pow(n,true+true)),n)))while((@compact(x)[x]->s[]=s[@compact(x)[x]->i++])and(@compact(x)[x]->s[]=(a.rray.un.re.chr(ord(u)+true).erse)(s[@compact(x)[x]->i++]))and(n>@compact(x)[x]->i)or(@die((json.un.encode)((a.rray.un.filter)(@compact(x)[x]->s)))))?>


@JörgHülsermann Since my regex was pretty long as it was and I don't expect it to have any chance to win, I just assumed that people won't get too hung up on such technicalities as the case sensitivity of the regex engine. Anyways, I edited my answer so the regex now includes a capital V. Have fun! :)
Ionut Botizan


1
@JörgHülsermann It is actually the same code but I initially used a looser regular expression because I was curious of what other solutions could people come up with. I'll give it one more day (maybe someone would like to take a shot at it over the week-end) and I'l post my code and the explanations tomorrow night. What I can tell you right now is that you were on the right path about using undefined constants as strings. Also, you were wrong about something in your solution. You can call (array_re.chr(ord(u)+true).erse)()! :) (...or at least you could when the _ was allowed)
Ionut Botizan

3
@IonutBotizan You could keep the solution of Level 1 secret for now since it is cracked. It is still better for you to make Level 2 as a new post, it is easier for other people to check whether it is cracked or not.
kennytm

1
level 2 cracked regex101.com/r/XtVl9G/1 thank you for the hint. Now I am waiting for level 3 :-)
Jörg Hülsermann

5

Ruby [cracked]

First Cops and Robbers challenge. Hope I didn't make this too easy.

EDIT: replaced \g<1> with (?1) because they're evidently equivalent in PCRE.

Regex(PCRE)

^(\W?\W\w){4}..(?1){2}[(-=Z-~]*(?1){5}\w*(?1)(.)\2$

Output (n=4)

[[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]]

(Returns an array of arrays. It's a lambda, BTW, but maybe that gives away too much?)



4

JavaScript (Cracked)

First time doing a Cops and Robbers challenge, hopefully doing it right.

Regex (JavaScript)

^.*(\.\w+\(.*\)){4}$

Output

An array equal to:

[[1,2,3,4],[8,7,6,5],[9,10,11,12],[16,15,14,13]]

You may want a $ on the end of the regex if the code itself ends at the end of the regex. Otherwise I could do e.g. x=>x.toString().toString().toString().toString() and then whatever I want after that.
ETHproductions

@ETHproductions Good point, thanks for the tip!
Tom


1
@ovs Wow, that was fast. Good job!
Tom

4
@Tom The .* at the beginning would've made it really easy. It could be any program followed by a comment. Basically, don't include .* in your regex.
mbomb007

4

Swift, regex 25 (Cracked)

Right, let's see if I've got the hang of this. This is my first cops and robbers post, so lemme know if I've messed up!

Regex

I used javascript flavour on regex101.com

^.{21}print[^/]{49}o.{7}$

Sample Output

[1, 2, 3, 4]
[8, 7, 6, 5]
[9, 10, 11, 12]
[16, 15, 14, 13]

Original Code

(0..<n).forEach{i in print((0..<n).map{i%2>0 ?(i+1)*n-$0 :i*n+$0+1},separator:",")}


It appears this submission doesn't take n as an input, but requires a hard coded variable. If that's correct then I'm afraid this is not valid according to meta consensus.
Stewie Griffin

Note: You may keep the post, since it's already been cracked :)
Stewie Griffin

@Stewie. Thanks for the info, there's a reason I've avoided these kinds of questions in the past! I think I understand the concept of "just a function" a bit better since this answer was cracked. I had assumed that it meant the body of a function, but I gather now it means a function variable?
James Webster

4

C – regex of 42 characters in length – cracked

Javascript regex as used in regex101.

^[-h<=*c+m?{printf("\/a: %d\\',o);}]{137}$

Guessing this will be trivial...

> main 4
1   2   3   4
8   7   6   5
9   10  11  12
16  15  14  13
>

Output is tab-delimited with \n after each line.

My solution, here integers 0 - 2 were obtained via t-t, t/t, and t:

main(int t,char**a){int o=t-t,i=t/t,m,n,h=atoi(*(a+i));for(m=o;m<h;m++)for(n=o;n<h;n++)printf("%d%c",m*h+(m%t?h-n:n+i),n<h-i?'\t':'\n');}

You can remove one r in your regex.
kennytm

@kennytm - thanks - missed that one


4

Jelly, length 14 cracked

cracked by Dennis

[^/P-`mvḊ-ṫ€]*

Python regex.

Added m back in again after I let it slip.

/ (reduce quick);
from P (product) to ` (monad from dyad quick);
m (modulo indexing);
v (eval dyad);
from (dequeue) to (tail); and
(for each quick)

For an input of 4 mine outputs:

 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13

...because I formatted a list of lists as a grid with G.


Cracked. This was a fun one.
Dennis

4

Powershell, 23 Bytes

Cracked By Matt

^.+?%.{42}%.{11}:.{35}$

Original Solution:

$n="$args";$script:r=0;$a=1..$n|%{$t=++$script:r..($script:r+=$n-1);if(!($_%2)){[Array]::Reverse($t)};,$t};$a|%{$_-join" "}

Takes input as argument and outputs to stdout

Hopefully this regex is OK, I don't expect this being too difficult to crack, as I haven't obfuscated much of it, and the regex gives a good few starting points to fill in the gaps, there's one thing in the first segment which is very uncommon in code golf though, which may catch someone out, I think a non-greedy match is required there to make this a bit tougher.

First cops challenge anyway.

1..4 | % { "----$_----" ; .\snake-cops.ps1 $_  }
----1----
1
----2----
1 2
4 3
----3----
1 2 3
6 5 4
7 8 9
----4----
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13


What was your solution?
Matt

@Matt added, I figured it would be harder considering how many non-code-golf things I added, i.e. using [Array]::Reverse() instead of $array[9..0] and $script:r variables which are mostly needless.
colsw

4

Röda 0.12, length 19 (Cracked by @KritixiLithos)

PCRE:

^{(\|[^\/#\s]*){8}$

Sample output (n=4):

[1, 2, 3, 4][8, 7, 6, 5][9, 10, 11, 12][16, 15, 14, 13]

Original code:

{|n|seq(0,n-1+n%2)|push([{|i|seq(n*i+1,n*i+n)}(_)],[{|j|seq(n*j+n,n*j+1,step=-1)}(_)])|head(n)}

Try it online!


1
It's fair game as long as it predates this challenge and has an available (free) interpreter. The first time I tried MATL was when trying to crack a cop post. Don't be surprised if someone learns Röda just to crack this answer :)
Stewie Griffin

I do hope the documentation is in English, not Finnish though :)
Stewie Griffin

@StewieGriffin There is some documentation available. Should I add a link to my answer or is is sufficiently easy to find from the Github page?
fergusq


4

PHP 7 (Safe)

Original Code

for($z=0,$q="";$z<($x=$argv[1])**2;){$w=($d=intdiv($z,$x))%2?($d+1)*$x-$z%$x:($z+1);for($f=0;$f<(log10($x**2)^0)-(log10($w)^0);$f++)$q.="\x20";$q.=++$z%$x?"$w\x20":"$w\n";}print(rtrim($q));

Second Try

Regex (PCRE): 29 Bytes

^[^A-Z#\/\s\>busy_heck]{189}$

No space, No comments, no use of base64_decode.

Many functions are not allowed! underscore

Output n=11

  1   2   3   4   5   6   7   8   9  10  11
 22  21  20  19  18  17  16  15  14  13  12
 23  24  25  26  27  28  29  30  31  32  33
 44  43  42  41  40  39  38  37  36  35  34
 45  46  47  48  49  50  51  52  53  54  55
 66  65  64  63  62  61  60  59  58  57  56
 67  68  69  70  71  72  73  74  75  76  77
 88  87  86  85  84  83  82  81  80  79  78
 89  90  91  92  93  94  95  96  97  98  99
110 109 108 107 106 105 104 103 102 101 100
111 112 113 114 115 116 117 118 119 120 121

Output n=4

 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13

Output n=3

1 2 3
6 5 4
7 8 9

I believe your answer is now safe :)
Aaron

@Aaron I wonder me that is was not cracked. Original Code is added
Jörg Hülsermann

4

MATL, length 12 (safe)

Regex

Uses Python flavour:

(\w{3}\W){5}

Example output

For n=4:

 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13

Solution

txU:GeG:oEq*S5M*TTx!

To see how this works, consider input n=4.

tx   % Implicit input n, duplicate, delete. So this does nothing
     % STACK: 4
U    % Square
     % STACK: 16
:    % Range
     % STACK: [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
Ge   % Reshape as an n-row array in column major order
     % STACK: [1  5  9 13;
               2  6 10 14;
               3  7 11 15;
               4  8 12 16]
G:   % Push range [1 2 ... n]
     % STACK: [1  5  9 13;
               2  6 10 14;
               3  7 11 15;
               4  8 12 16]
               [1 2 3 4]
o    % Modulo 2
     % STACK: [1  5  9 13;
               2  6 10 14;
               3  7 11 15;
               4  8 12 16]
              [1  0  1  0]
Eq   % Times 2, minus 1 (element-wise)
     % STACK: [1  5  9 13;
               2  6 10 14;
               3  7 11 15;
               4  8 12 16]
              [1 -1  1 -1]
*    % Multiply (element-wise with broadcast)
     % STACK: [1 -5  9 -13;
               2 -6 10 -14
               3 -7 11 -15
               4 -8 12 -16]
S    % Sort each column
     % STACK: [1 -8  9 -16;
               2 -7 10 -15;
               3 -6 11 -14;
               4 -5 12 -13]
5M   % Push [1 -1 1 -1] again
     % STACK: [1 -8  9 -16;
               2 -7 10 -15;
               3 -6 11 -14;
               4 -5 12 -13]
              [1 -1  1  -1]
*    % Multiply (element-wise with broadcast)
     % STACK: [1  8  9  16;
               2  7 10  15;
               3  6 11  14;
               4  5 12  13]
TTx  % Push [true true] and delete it. So this does nothing
!    % Transpose. Implicitly display
     % STACK: [ 1  2  3  4;
                8  7  6  5;
                9 10 11 12;
               16 15 14 13]

4

Jelly, length 17 (safe)

[^/P-`mvÇ-ıḃ-ṫ€]*

Python regex.

Tightening the knot, this bans some more useful things, for your aid here are the banned bytes:

/PQRSTUVWXYZ[\]^_`mvÇÐÑ×ØÞßæçðñ÷øþĊċĖėĠġİıḃḄḅḊḋḌḍḞḟḢḣḤḥḲḳḶḷṀṁṂṃṄṅṆṇṖṗṘṙṚṛṠṡṢṣṪṫ€

just under a third of them!

For an input of 4 mine outputs:

 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13

...because I formatted a list of lists as a grid with G.

A solution:

’:2o1
Ḃ¬aẋ@0
’r0;0ẋ$ẋ1Ŀ¬0¦;2ĿÆ¡œ?⁸²¤s⁸G

Try it online! / regex101

The main trick here is to index into a lexicographically sorted list of the permutations of the natural numbers up to n2 (using œ? to avoid building the list of length n2!), and to split the result into chunks of length n. The aforementioned index is found by forming its representation in the factorial number system which is formulaic since the "unsliced" snake is created by permuting elements in a prescribed manner (this may be readily converted to a number with Æ¡).

The solution I present uses Ŀ to reference previous links as monads (replacing Ñ and Ç), but multiple $ in a row could be employed instead to "inline" these helper functions. It also uses r since and R are banned.

’:2o1 - Link 1, periodic repetitions in the factorial base representation: n
’     - decrement n
 :2   - integer divide by 2
   o1 - or 1 (keep one period in the cases n=1 and n=2)

Ḃ¬aẋ@0 - Link 2, n zeros if n is even, else an empty list: n
Ḃ      - mod 2
 ¬     - not
   ẋ@0 - 0 repeated n times
  a    - and

’r0;0ẋ$ẋ1Ŀ¬0¦;2ĿÆ¡œ?⁸²¤s⁸G - Main link: n                    e.g. 6
’r0                        - inclusive range(n-1, 0)              [5,4,3,2,1,0]
    0ẋ$                    - 0 repeated n times                   [0,0,0,0,0,0]
   ;                       - concatenate (makes one "period")     [5,4,3,2,1,0,0,0,0,0,0,0]
        1Ŀ                 - call link 1 as a monad               2
       ẋ                   - repeat list                          [5,4,3,2,1,0,0,0,0,0,0,0,5,4,3,2,1,0,0,0,0,0,0,0]
           0¦              - apply to index 0 (rightmost index):
          ¬                -     not (make the last 0 a 1)        [5,4,3,2,1,0,0,0,0,0,0,0,5,4,3,2,1,0,0,0,0,0,0,1]
              2Ŀ           - call link 2 as a monad               [0,0,0,0,0,0]
             ;             - concatenate                          [5,4,3,2,1,0,0,0,0,0,0,0,5,4,3,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0]
                Æ¡         - convert from factorial base          45461852049628918679695458739920
                      ¤    - nilad followed by link(s) as a nilad
                    ⁸      -     left argument, n                 6
                     ²     -     square                           36
                  œ?       - lexicographical permutation lookup   [1,2,3,4,5,6,12,11,10,9,8,7,13,14,15,16,17,18,24,23,22,21,20,19,25,26,27,28,29,30,36,35,34,33,32,31]
                       s⁸  - split into chunks of length n        [[1,2,3,4,5,6],[12,11,10,9,8,7],[13,14,15,16,17,18],[24,23,22,21,20,19],[25,26,27,28,29,30],[36,35,34,33,32,31]]
                         G - format as a grid

4

Pip, regex length 3 (safe)

The solution is a full program that takes n as a command-line argument. It does not use any command-line flags.

Regex (any flavor)

\w+

Sample output

1 2 3 4 
8 7 6 5 
9 10 11 12 
16 15 14 13 

My solution

YENsXaPBsPOyY_MUyFi_MUENsXaIiBA1PsPUPODQENsXiXaPBsX_PBsMRVyEI1PsPUPODQENsXiXaPBsX_PBsMy

Try it online!

Strategy

Here's the code we would like to write:

Y \,a
F i ,a
 I i%2
  P i*a+_.s M RVy
 E
  P i*a+_.s M y

That is:

  • Store the numbers 1 through a in y
  • Loop over values of i from 0 through a-1
  • If i is odd, reverse y, add i*a to each element, concatenate a space to each element, and print
  • Otherwise, do the same thing, but without reversing first

Difficulties

A lot of commands and variables in Pip use letters, but some important ones don't:

  • Range and inclusive range (, and \,)
  • Most math operations (+, -, *, %, ++)
  • Assignment (:)
  • We can't have a loop or function body with more than one statement (that would need {})
  • We can't use parentheses to enforce precedence

How we get around those limitations:

  • ENumerate can be used in place of ,; we just need a string with the number of characters we want, and we need to extract the first element of each sublist in a structure like [[0 "H"] [1 "i"]].
  • We don't need to increment anything if we can solve the problem with For loops.
  • We can assign to the y variable with the Yank operator.
  • We can do math with strings: X is string multiplication, and PUsh (or PB "push-back") will concatenate a string to another string in-place. To take the length of a string, we can ENumerate it and extract the right number from the resulting list.
  • We can use functions as long as they can be written as single-expression lambda functions using _.

Specifics

The building blocks of our program:

Range

_MUENsXa

That's map-unpack(_, enumerate(repeat(space, a))) in pseudocode. Map-unpack is like Python's itertools.starmap: given a list of lists, it calls a function on the items of each sublist. _ returns its first argument, so _MU just gets the first item of each sublist. For example, if a = 3:

     sXa  "   "
   EN     [[0 " "] [1 " "] [2 " "]]
_MU       [0 1 2]

... which is the same as ,a.

Inclusive range

I'm not sure there's a way to do inclusive-range(1, a) in a single expression, but fortunately we only need it once, so we can construct it in the y variable in three steps.

YENsXaPBs

In pseudocode, yank(enumerate(repeat(space, a).push-back(space))):

   sXa     "   "
      PBs  "    "
 EN        [[0 " "] [1 " "] [2 " "] [3 " "]]
Y          Store that in y

Next POy pops the first item from y and discards it, leaving [[1 " "] [2 " "] [3 " "]].

Finally,

Y_MUy

That is, yank(map-unpack(_, y)): extract the first element of each sublist and yank the resulting list back into y. y is now [1 2 3].

Length

PODQENaPBs

In pseudocode, pop(dequeue(enumerate(a.push-back(space)))). The difficulty here is that enumerate only gives us numbers up to len(a)-1, but we want len(a). So we first push a space to a, lengthening it by one character, and then take len-1 of the new string.

      a     "xyz"
       PBs  "xyz "
    EN      [[0 "x"] [1 "y"] [2 "z"] [3 " "]]
  DQ        [3 " "]
PO          3

Math

Now that we have a way to take the length of strings, we can use strings to do multiplication and addition of numbers:

PODQENsXaXbPBs
PODQENsXaPBsXbPBs

The first does sXaXb to create a string of a*b spaces and then takes the length of it; the second does sXaPBsXb to push a string of b spaces to a string of a spaces and then takes the length of it.

The nice part is that all the operators we're using here (PU, PO, PB, DQ, EN, X) can be used with _ to form lambda expressions. So we can map mathematical transformations to the inclusive range we constructed earlier.

We also need to check i%2 inside the loop, but this is easily accomplished with bitwise AND: iBA1.

Put them together

The full code, with some added whitespace:

YENsXaPBs POy Y_MUy              Get \,a into y
F i _MUENsXa                     For i in ,a
 I iBA1                           If i%2=1
  P sPUPODQENsXiXaPBsX_PBs M RVy   Print sPUi*a+_ M RVy
 EI1                              Elseif 1 (using E would cause a parsing problem)
  P sPUPODQENsXiXaPBsX_PBs M y     Print sPUi*a+_ M y

Are we allowed to use flags such as -S?
Brian McCutchon

@BrianMcCutchon Good question: answer is no. (Since they're not part of the code subject to the regex, it seemed too loophole-ish to use them.) Edited to clarify.
DLosc

So far I have that a*b is _V_VRVENCGaRLbPU1, ,a is _MUENZGa, aJ" " is aJ_VRVk, and a@i is something like _V_VRVaZCGi, though I can't quite work out the precedence without parentheses yet. Also, a vague idea that I can get the permutations of a range (created as above, using the equivalent of ,(a*a)) and use that to select the correct permutation for each row.
Brian McCutchon

@BrianMcCutchon I can't comment on any specifics, of course, but I'm really enjoying the progress update. ^_^
DLosc

I think it's safe now. How'd you do it?
Brian McCutchon

3

CJam, PCRE, length 8, cracked

^[a-~]*$

Example output for 4:

[[1 2 3 4] [8 7 6 5] [9 10 11 12] [16 15 14 13]]

Cracked. Nice idea. :) There seem to be quite a lot of approaches that work, I wonder what you had in mind.
Martin Ender

My answer actually satisfies a tighter regex — I’ll show it when that one gets cracked!
Lynn

3

CJam, PCRE, length 9, cracked

^[a-z~]*$

Example output for 4:

[[1 2 3 4] [8 7 6 5] [9 10 11 12] [16 15 14 13]]

Now {|} are banned, too.



Good job! My answer was basically the same, except it only used a bunch of me and mq to approximate the number, so it was like, extremely (~20k bytes) long.
Lynn


3

tinylisp, regex length 3 (cracked)

You can test tinylisp code at Try it online!

Regex (any flavor)

\S+

Time to go hardcore.

Output

The solution defines a function that takes a single integer argument and returns a list like this (for n=4):

((1 2 3 4) (8 7 6 5) (9 10 11 12) (16 15 14 13))

My original code uses the same basic idea Brian McCutchon came up with, building lists and eval'ing them. Here it is in one line:

(v(c(h(q(d)))(c(h(q(d')))(c(c(h(q(q)))(c(c()(c(q(arglist))(c(c(h(q(v)))(c(c(h(q(c)))(c(c(h(q(q)))(q(d)))(q(arglist))))()))())))()))()))))(d'(seq-args(c(h(q(start)))(c(h(q(stop)))(c(h(q(step)))())))))(d'(seq(c(c(h(q(accum)))seq-args)(q((i(e(v(h(q(start))))stop)(c(v(h(q(start))))accum)(seq(c(v(h(q(stop))))accum)start(s(v(h(q(stop))))step)step)))))))(d'(f'(c(c(h(q(index)))(c(h(q(size)))seq-args))(q((i(e(v(h(q(index))))size)()(c(seq()start(v(h(q(stop))))step)(f'(a(h(q(1)))index)size(a(v(h(q(stop))))size)(a(v(h(q(start))))size)(s(h(q(0)))step)))))))))(d'(f(q((size)(f'(h(q(0)))size(h(q(1)))size(h(q(1))))))))

I used the full construct-and-eval method once, to define a macro d' that makes definitions like d, but takes its arguments wrapped in a list: so instead of (d x 42), you can do (d'(x 42)). Then it was just a matter of rewriting any lists in the definitions that might need whitespace: (q(a b)) -> (c a(q(b))) -> (c(h(q(a)))(q(b))).


1
Cracked. It wasn't easy.
Brian McCutchon

2

Python3, length 162 (Cracked!)

Regex: ^([^"' #]){24}"(?1){11}i%n(?1){4}2\*n-(?1){4}i%n(?1){10}i\/n(\)\/\/1)(?1){5}(?2)(?1){3}2\*\(i%n\)(?1){4}[int()2\/]{16}for i in range\(j,(?1){4}\]\)(?1){6}\"\*n\)$

Okay, I know, it's quite long. Fortunately, it won't be cracked in under a week... :'D.

I think I didn't make a mistake anywhere, that would allow loophole-y answers.

Output format

4:
[1, 2, 3, 4]
[8, 7, 6, 5]
[9, 10, 11, 12]
[16, 15, 14, 13]

Original code:n=int(input());j=0;exec("print([int(i%n+1+(2*n-(2*(i%n)+1))*((((i/n)//1+1)/2)//1)+(2*(i%n)+1)*int(int(i/n)/2))for i in range(j,j+n)]);j+=n;"*n)


En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.