Tourne-moi 22,5 avec une rose


39

Soit une ficelle qui est l’une des directions d’une boussole à 16 points

16-point compass rose

émet les deux directions immédiatement adjacentes à la direction d’entrée, dans le sens des aiguilles d’une montre.

Plus précisément, vous devez gérer ces paires d’entrées / sorties (et uniquement celles-ci):

Input  Output
N      NNW NNE
NNE    N NE
NE     NNE ENE
ENE    NE E
E      ENE ESE
ESE    E SE
SE     ESE SSE
SSE    SE S
S      SSE SSW
SSW    S SW
SW     SSW WSW
WSW    SW W
W      WSW WNW
WNW    W NW
NW     WNW NNW
NNW    NW N

La sortie peut être une chaîne avec un délimiteur (pas rien) entre les directions ou une liste à deux éléments. La direction immédiatement à gauche de l’entrée doit apparaître en premier. Vous pouvez utiliser des lettres minuscules pour les instructions au lieu de majuscules, mais conservez toutes les entrées et sorties dans un cas ou dans l'autre.

Par exemple, pour l'entrée N(ou nsi vous utilisez des minuscules), certaines sorties valides sont:

NNW NNE
NNW-NNE
["NNW", "NNE"]
nnw-nne (if using lowercase)

Certaines sorties non valides sont:

NNWNNE
NNE NNW
nnwNNE
NNw NNe

Le code le plus court en octets gagne.

Réponses:


12

Gelée , 37 à 34 octets

“¢ ¬9£Hæz¥{çb¤S®!‘ṃ€“¡&¦»
¢iµ’,‘ị¢

Essayez-le en ligne!

Prend en minuscule.

-2 grâce à Jonathan Allan .
-1 puisqu'il s'avère que cette fonction est valide :)

Grâce à Jonathan Allan (et Dennis), vous pouvez maintenant supprimer le fichier . Malheureusement, ce ne serait pas en concurrence ici.

Explication détaillée de l'algorithme :

Nous commençons habituellement à expliquer en partant du bas (lien principal) en descendant, mais j'estime qu'il est plus approprié d'expliquer en partant du haut.

Premièrement, nous chargeons simplement la liste [1, 32, 7, 57, 2, 67, 17, 92, 3, 94, 19, 119, 4, 109, 9, 34]. Cela ressemble à des nombres aléatoires hein? Eh bien, il s’agit en fait d’une liste de nombres compressés en base 5; nous le décompressons donc en base 5. Maintenant ça ressemble [[1], [1, 1, 2], [1, 2], [2, 1, 2], [2], [2, 3, 2], [3, 2], [3, 3, 2], [3], [3, 3, 4], [3, 4], [4, 3, 4], [4], [4, 1, 4], [1, 4], [1, 1, 4]]. Toujours des éléments aléatoires, mais il s'agit en fait d'une NESWliste cartographiée des seize coordonnées, de sorte que nous ne sommes pas loin de la compléter (Jelly est indexée 1). Nous obtenons le mappage final [['N'], ['N', 'N', 'E'], ['N', 'E'], ['E', 'N', 'E'], ['E'], ['E', 'S', 'E'], ['S', 'E'], ['S', 'S', 'E'], ['S'], ['S', 'S', 'W'], ['S', 'W'], ['W', 'S', 'W'], ['W'], ['W', 'N', 'W'], ['N', 'W'], ['N', 'N', 'W']], qui correspond à la liste complète que nous souhaitons (les chaînes Jelly sont sous la forme [char1, char2, char3, ...].)

Depuis que nous avons construit la liste de coordonnées, nous travaillons avec elle. Le lien principal entre en jeu. Tout d'abord, nous chargeons la liste que nous avons construite, puis prenons l'index dans lequel se trouve la coordonnée d'entrée (en tant qu'argument de ligne de commande). Ensuite, nous lions son prédécesseur et son successeur dans une liste, et nous les utilisons en tant que modulaires. index dans la même liste de coordonnées pour prendre les coordonnées à gauche et à droite de l’entrée, respectivement. Vous penseriez maintenant que nous avons enfin terminé, mais il y a en fait une dernière chose, le séparateur. Ceci est valable en tant que fonction, puisque 1) vous pouvez l'appeler en utilisant <integer>Ŀ2) Vous pouvez également définir d'autres fonctions (comme l'importation de modules). Maintenant, nous avons fini. En tant que programme complet, il n'y a pas de séparateur, mais ce n'est pas grave, car cela fonctionne comme une fonction.

Explication du code lien par lien :

¢iµ’,‘ị¢K Main link. Arguments: z = cmd0
¢         Run the helper link niladically (i.e. load the coordinate list).
 i        Find the index of z in the list.
  µ       Start a new monadic chain. Arguments: z = list_index.
   ’      Decrement z.
     ‘    Increment z.
    ,     Pair x and y into [x, y].
       ¢  Run the helper link niladically.
      ị   Take the elements of y at the indices in x.

“¢ ¬9£Hæz¥{çb¤S®!‘ṃ€“¡&¦» Helper link. Arguments: [1, 32, 7, 57, 2, 67, 17, 92, 3, 94, 19, 119, 4, 109, 9, 34]
“¢ ¬9£Hæz¥{çb¤S®!‘        Generate the integer list (the argument).
                    “¡&¦» Literal "newsy".
                  ṃ€      Base-length(y)-decompress every integer in x, then index into y.


11

Mathematica, 118 112 octets

Merci à Martin Ender d'avoir économisé 6 octets!

r=StringSplit@"N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW N NNE";<|Array[r[[#]]->r[[#+{-1,1}]]&,16,2]|>

Fonction sans nom (une association, en réalité) qui prend une chaîne en tant qu'entrée et renvoie une paire ordonnée de chaînes. En gros, il suffit de coder en dur la réponse.


8

Python 2, 116 115 103 bytes

-12 bytes thanks to Neil

d='N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW'.split()
n=d.index(input())
print d[n-1],d[n-15]

Try it Online!


2
Use d[n-15] to avoid the condition.
Neil

1
By the way, there's an extraneous quote at the end of the code segment in your answer. I would put in an edit request myself, but the edit has to be at least six characters and this would only be one.
notjagan

1
@Neil Thanks! Saved a lot of bytes :)
math junkie

1
@notjagan Thanks for pointing that out. Fixed it
math junkie

8

JavaScript ES6, 106 102 bytes

p=>[(a=`N|NNE|NE|ENE|E|ESE|SE|SSE|S|SSW|SW|WSW|W|WNW|NW|NNW`.split`|`)[i=a.indexOf(p)-1&15],a[i+2&15]]

Try it online!

const f = p=>[(a=`N|NNE|NE|ENE|E|ESE|SE|SSE|S|SSW|SW|WSW|W|WNW|NW|NNW`.split`|`)[i=a.indexOf(p)-1&15],a[i+2&15]]

console.log(f('N'))
console.log(f('NNE'))
console.log(f('ENE'))
console.log(f('E'))
console.log(f('ESE'))
console.log(f('SE'))
console.log(f('SSE'))
console.log(f('S'))
console.log(f('SSW'))
console.log(f('SW'))
console.log(f('WSW'))
console.log(f('W'))
console.log(f('WNW'))
console.log(f('NW'))
console.log(f('NNW'))


Save 2 bytes with let instead of const.
HonoredMule

1
-4 bytes by moving variable declarations to where they are first used, Try it Online
fəˈnɛtɪk

7

05AB1E, 44 43 bytes (Thanks to Adnan)

"ESNW4"•2ßU^]>Þ‡¾“¾&é{½‡•5BSè4¡©skD<®ès>®è)

Try it online!

"ESNW4"•2ßU^]>Þ‡¾“¾&é{½‡•5BSè # Push N4NNE4NE4ENE4E4ESE4SE4SSE4S4SSW4SW4WSW4W4WNW4NW4NNW
4¡©            # Split on 4's and store.
   sk          # Index of input in direction array.
     D<®è      # Element before index of input.
         s>®è  # Element after index of input.
             ) # Wrap two element to array.

Exmaple output:

N => [NNW,NNE]

Version that pushes N0NNE0NE0ENE0E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW instead:

•17¿$Mn]6VAÆ—Dªd—•5B4LJ"NSWE"‡0¡©skD<®ès>®è)

Is also 44-bytes, there was 0 reason for my refactor and there is 0 reason for splitting on the 4's.



1
Any special reason to split on 4s?
Greg Martin

@GregMartin •17¿$Mn]6VAÆ—Dªd—•5B4LJ"NSWE"‡0¡©skD<®ès>®è) turns out that, no, there is no reason at all. Using 0 as the delimiter is the same compression ratio, as it doesn't drop the length of the number in the base-5 conversion to base-214. Coulda sworn doing it like that saved me a byte though.
Magic Octopus Urn

You can do „ €Ã¦•174SÝ©l2ÎG¦˜fÐ98•5BSè#ÐIk©<ès®>è) to save 4 bytes.
Emigna

7

Javascript - 234 154 156 152 120 106 102 bytes

Only my second time doing code golf!!

Latest Revision:

Thank you to @fəˈnɛtɪk for this neat variable trick!

s=>[(a=`NNW N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW`.split` `)[n=a.indexOf(s)-1&15],a[n+2&15]]

Before That: Okay so latest revision: Input is a string and output is a string which is in the rules, so I made it into a function, and with reductions I have gone even smaller (also function is anonymous, which now means mine has somehow meshed into the other js answer oops! He (powelles) had it first!!):

(s,a=`NNW N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW`.split` `,n=a.indexOf(s))=>[a[n-1&15],a[n+1&15]]

Can be used by:

f=(s,a=`NNW N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW`.split` `,n=a.indexOf(s))=>[a[n-1&15],a[n+1&15]]
alert(f(prompt()))

Remade (not function) with Output - 120:

a="NNW N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW".split(' ');n=a.indexOf(prompt());alert(a[n-1&15]+' '+a[n+1&15]);
  • Note that I made an error originally, having it equal a.length instead of a.length-1 for the first index. Thanks @Neil for pointing out that it didn't work for NNW.

  • Note 2: Thank you to @Neil and @ETHProductions for helping me shorten the code!

Originial:

a="NNWN  NNENE ENEE  ESESE SSES  SSWSW WSWW  WNWNW ";l=prompt("","");n=l.length<3?l.length<2?l+'  ':l+' ':l;f=a.indexOf(n);i=f-3;j=f+3;i=i<0?a.length+--i:i;j=j+3>=a.length?j-a.length:j;alert(a.substring(i,i+3)+' '+a.substring(j,j+3));

1
Welcome back to golfworld!
Greg Martin

1
This doesn't work for NNW.
Neil

@Neil You are correct. I will fix it!
Blue Okiris

1
I was working towards my own solution before I realised it was very similar to yours. A few tips for you: 1) Anonymous functions are valid, 2) You don't need to request an input in your submission, it just needs to be able to receive one, 3) You don't need to log the output in your submission, simply return. With all that in mind, here's the 106 characters I was down to for you to improve your solution with: p=>(a="N,NNE,NE,ENE,E,ESE,SE,SSE,S,SSW,SW,WSW,W,WNW,NW,NNW".split,,i=a.indexOf(p),[a[i-1&15],a[i+1&15]])
Shaggy

1
-4 bytes by moving variable declarations into where they are used, Try it Online
fəˈnɛtɪk

3

Batch, 196 bytes

@set s=N
@if %1==N echo NNW
@for %%r in (NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW)do @call:c %1 %%r
@if %1==NNW echo N
@exit/b
:c
@if %1==%2 echo %s%
@if %1==%s% echo %2
@set s=%2

Loops through each pair of compass points, printing one when the other matches. For example, for a parameter of ENE, when the loop reaches ENE, the variable s contains NE which is printed, then when the loop advances to E, the variable s contains ENE and so E is printed. One pair then needs to be special-cased to avoid the compass points from being printed in the wrong order.


3

Jelly,  40 38 bytes

“NSWE”“dḍ.ƈ€ḶƘfƥ’ṃṁ
“¢)`)’ḃ3RÇṙi¥µṖṪ,Ḣ

Try it online! (added the footer to show the output is a list of two items) ...or see all cases.

(I'm not quite sure why 1323DRẋ4 in place of “¢)`)’ḃ3R doesn't work at the moment.)

How?

“NSWE”“dḍ.ƈ€ḶƘfƥ’ṃṁ - Link 1, rose list helper: shape array
“NSWE”              - "NSWE"
      “dḍ.ƈ€ḶƘfƥ’   - base 250 number: 1554210846733274963415
                 ṃ  - base decompress: "NNNENEENEEESESESSESSSWSWWSWWWNWNWNNW"
                  ṁ - mould like shape array

“¢)`)’ḃ3RÇṙi¥µṖṪ,Ḣ - Main link: direction string
“¢)`)’             - base 250 number: 33899292
      ḃ3           - to base 3: [1,3,2,3,1,3,2,3,1,3,2,3,1,3,2,3]
        R          - range (vectorises) [[1],[1,2,3],[1,2],[1,2,3],[1],[1,2,3],[1,2],[1,2,3],[1],[1,2,3],[1,2],[1,2,3],[1],[1,2,3],[1,2],[1,2,3]]
         Ç         - call the last link (1) as a monad: ["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"]
            ¥      - last two links as a dyad
          ṙ        -     rotate the list by:
           i       -         index of the direction string in the list
             µ     - monadic chain separation (call the rotated list x)
              Ṗ    - pop (x[:-1]) (removes the direction string)
               Ṫ   - tail that (i.e. x[-2])
                 Ḣ - head x (i.e. x[0])
                ,  - pair

3

Haskell, 100 99 bytes

s=words"N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW"++s
(a:b:c:r)#x|x==b=(a,c)|1<3=r#x
(s#)

Try it online! Calling (s#) "N" returns ("NNW","NNE").

s is an infinite repetition of the list of directions, thus we don't have to add an extra N and NNE like some of the other answers to correctly handle the edges of the list.

Thanks to @nimi for saving one byte!


1
An infix function saves a byte: (a:b:c:r)!x| ... =r!x;(s!).
nimi

2

SOGL, 33 bytes

≠┐πΜ]ρ½d⁹V¹-┐*╔╤¹Ψæ;¶‘θ,W:AHwOaIw

The first part ≠┐πΜ]ρ½d⁹V¹-┐*╔╤¹Ψæ;¶‘ is a compressed string that is

N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW

compressed with a custom dictionary with ENSW

The rest of the program:

...‘θ,W:AHwOaIw  example input: NNW
...‘             push the compressed string        ["N NNE NE ... NNW"]
    θ            split on spaces                   [["N","NNE",...,"NNW"]]
     ,W          get the index of input            [["N","NNE",...,"NNW"], 16]
       :A        save the index on variable A      [["N","NNE",...,"NNW"], 16]
         H       decrease [the index]              [["N","NNE",...,"NNW"], 15]
          wO     output that'th item of the array  [["N","NNE",...,"NNW"]]
            a    load variable A                   [["N","NNE",...,"NNW"], 16]
             I   increase [the index]              [["N","NNE",...,"NNW"], 17]
              w  get that item in the array        [["N","NNE",...,"NNW"], "N"]

What code page?
Joshua

@Joshua The bytes in the title has a link to the codepage
dzaima

@Joshua Actually, that was missing a couple of characters because of markdown , but it's fixed now
dzaima

2

PHP, 122 bytes

preg_match("/([^ ]+ )$argv[1] ([^ ]+)/",'N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW N NNE',$m);
echo $m[1].$m[2];

1
You can save 2 bytes removing unnessary whitespaces. -3 bytes for replacing $argv[1] with $argn and using the -R option. if you use deprecated functions if could be ending in ereg("([^_]+)_{$argn}(_[^_]+)",N_NNE_NE_ENE_E_ESE_SE_SSE_S_SSW_SW_WSW_W_WNW_NW_NNW_N_NNE,$t);echo$t[1].$t[2];
Jörg Hülsermann

1

Ruby - 94 Bytes

A riff on Blue Okiris's answer, just to take advantage of some nice Ruby shorthand (the %w[] syntax and p specifically):

->(s,d=%w[N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW],n=d.index(s)){p d[n-1],d[n-15]}

1

Japt, 66 52 bytes

Saved 14 bytes thanks to @ETHproductions

V=`ã@JaÀTeaÀÄsÁÁss°s°ws°°wn°n°nnw`qa [J1]£VgX+VaU

Try it online!

Explanation:

V=(`...`qa) [J1]£Vg(X+VaU)
V=(       )                // Set V to:
   `...`                   //   "nanneaneaeneaeaeseaseasseasasswaswawswawawnwanwannw" (de-)compressed
        qa                 //    Split on "a", creating [n...nnw]
            [J1]           // [-1,1]
                £          // Iterate through ^, X becomes the iterative item
                 Vg(     ) //   V.Item at index:
                    X+VaU  //     X + V.indexOf(input)

Very nice. A couple improvements: 1) You can take the input in lowercase instead of converting the array to uppercase. 2) You can actually remove the ' in q'o and it will work exactly the same :-)
ETHproductions

Also, you can reduce the array construction at the end to [J1]£VgX+VaU to save a few bytes
ETHproductions

@ETHproductions That is brilliant, thanks!
Oliver


1

PHP, 115 Bytes

for($r=explode(_,($w=N_NNE_NE_ENE_E_ESE_SE_SSE_).strtr($w,SWNE,NESW).$w);$r[++$i]!=$argn;);echo$r[$i-1]._.$r[$i+1];

-2 Bytes using the deprecated function split instead of explode

PHP, 128 Bytes

for($i=2;$i--;print$i?end($e)._:$e[2])$e=explode(_,strstr(($w=N_NNE_NE_ENE_E_ESE_SE_SSE_).strtr($w,SWNE,NESW).$w,_.$argn._,$i));

PHP, 134 Bytes

echo($r=explode(_,N_NNE_NE_ENE_E_ESE_SE_SSE_S_SSW_SW_WSW_W_WNW_NW_NNW))[($k=array_search($argn,$r))-1<0?15:$k-1]._.$r[$k+1>15?0:$k+1];

1

PHP, 110 109 bytes

Saved 1 byte thanks to Jörg Hülsermann.

echo@preg_filter("/.*?(\w+) $argn( \w+).*/",'$1$2',($s='N NNE NE ENE E ESE SE SSE ').strtr($s,NESW,SWNE).$s);

2
You could replace preg_replace with preg_filter to save 1 byte
Jörg Hülsermann

0

Python 3 - 112 107 bytes

I based this off of my Javascript answer:

Remade:

lambda i,s="N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW".split():[s[s.index(i)-1],s[s.index(i)-15]]

Use as say

f = lambda i,s="N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW".split():[s[s.index(i)-1],s[s.index(i)-15]]
print(f(input()));

Original:

lambda i,s="N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW".split():[s[s.index(i)-1&15],s[s.index(i)+1&15]]

0

MATL, 43 bytes

';evl(Z?&fWElf`gvhM'F' NESW'ZaYbtjY=fFTEq+)

Try it online!

Explanation

';evl(Z?&fWElf`gvhM' % Push this string
F                    % Push false
' NESW'              % Push this string
Za                   % Base conversion. This decompresses the first string from alphabet
                     % given by all printable ASCII except single quote to the alphabet
                     % ' NESW'. The result is the following string, which is pushed:
                     % 'N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW'
Yb                   % Split at spaces. Gives a cell array of strings
t                    % Duplicate
j                    % Input string
Y=                   % String comparison. Gives an array containing true at the index
                     % of the matching string
f                    % Find: index of the entry that equals true
FTEq                 % Push [-1 1] (obtained as [false true], times 2, minus 1)
+                    % Add, element-wise
)                    % Index modularly into the cell array of strings
                     % Implicitly display. Each cell is displayed on a different line

0

c, 222 216 211 bytes

main(c,v)char**v;{char r[]="NXNNEXNEXENEXEXESEXSEXSSEXSXSSWXSWXWSWXWXWNWXNWXNNWX",*p=r,*s=r,*a[16],i=0,n;for(;*p++;)*p==88?*p=0,n=strcmp(a[i++]=s,v[1])?n:i-1,s=++p:0;printf("%s %s\n",a[n?n-1:15],a[n<15?n+1:0]);}

Try it online


0

Javascript (ES6), 189 bytes

d="N.NNW NNE.NNE.N NE.NE.NNE ENE.ENE.NE E.E.ENE ESE.ESE.E SE.SE.ESE SSE.SSE.SE S.S.SSE SSW.SSW.S SW.SW.SSW WSW.WSW.SW W.W.WSW WNW.WNW.W NW.NW.WNW NNW.NNW.NW N".split`.`,f=>d[d.indexOf(f)+1]

Just takes the input, looks it up, and returns it.


0

JavaScript (ES6), 94 bytes

Expects a string in uppercase such as "ENE". Returns a comma separated string such as "NE,E".

s=>/\D+,\D+/.exec('NNW0N0NNE0NE0ENE0E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW0N'.split(0+s+0))[0]

How it works

The expression 0+s+0 is coerced to a string when split() is called. For instance, if the input is "ENE", the string will be split on "0ENE0":

"NNW0N0NNE0NE0ENE0E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW0N"
             ^^^^^

This leads to the following array:

[ "NNW0N0NNE0NE", "E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW0N" ]

Again, this array is coerced to a string when exec() is called. So, the regular expression is actually applied on:

"NNW0N0NNE0NE,E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW0N"

We look for consecutive non-numeric characters (\D+) followed by a comma, followed by consecutive non-numeric characters. This returns the array [ "NE,E" ]. We could arguably stop there and return just that. But the challenge is asking for either a delimited string or a two-element array. So, we extract the string with [0].

Demo


0

Pyth, 39 bytes:

.rL]z_Bms@L"ESWN"jCd5"\"❤m❤w❤^❤\❤C❤9❤ ❤

where represents unprintable letters.

Try it online!

Hexdump:

0000000: 2e 72 4c 5d 51 5f 42 6d 73 40 4c 22 45 53 57 4e .rL]Q_Bms@L"ESWN
0000010: 22 6a 43 64 35 22 5c 22 09 6d 04 77 13 5e 03 5c "jCd5"\".m.w.^.\
0000020: 11 43 02 39 07 20 01                            .C.9. .
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.