Mappa del tesoro Disegno Bot


14

Stai organizzando una caccia al tesoro per i tuoi amici. Per condurre le cose più facilmente, vuoi disegnare una mappa di tutti i luoghi in cui hai nascosto gli oggetti preziosi.

Ingresso

È 0 0consentita qualsiasi forma di input che indica un elenco di punti costituiti da coordinate xe y (non negative), essendo l'angolo in alto a sinistra (Nota: è possibile utilizzare anche l'indicizzazione basata su 1 nella risposta, si prega di commentare che se si ). Esempio:

1 2
3 0
0 1

Sfida

La tua funzione o programma dovrebbe essere in grado di costruire una mappa che denota ogni data posizione con un punto in xcui si trova il segno nella riga y + 1 e nella colonna x + 1 nell'output. Le posizioni non contrassegnate sono rappresentate con a . La mappa è inoltre composta da una cornice in cui gli angoli sono +s, le linee verticali sono se |le linee orizzontali sono -s. La tua soluzione dovrebbe produrre il frame più piccolo possibile. Mappa per l'esempio di input fornito sopra:

+----+
|   x|
|x   |
| x  |
+----+

Possibili casi di test


"0 0"
=>
+-+
|x|
+-+

"0 10
 5 5
 10 0"
=>
+-----------+
|          x|
|           |
|           |
|           |
|           |
|     x     |
|           |
|           |
|           |
|           |
|x          |
+-----------+

""
=>
++
++

"0 0
 0 2
 2 0"
=>
+---+
|x x|
|   |
|x  |
+---+

Ovviamente, questo è , il che significa che vince la soluzione con il numero di byte più basso! Le spiegazioni della tua soluzione sono incoraggiate.


Non proprio, ma non potevo davvero pensare a un altro formato di input. Ma sono disposto a cambiarlo se giova alla sfida.
— racer290,

Possono esserci mappe non quadrate?
— FrownyFrog,

4
@ racer290 Suggerirei solo di dire qualcosa del generethe input is a list of locations (e.g. nested list, list of tuples, space & newline separated, separate inputs, ect.)
— dzaima,

1
L'output può essere un array di caratteri 2D?
— Ovs

2
Posso inviare una funzione prendendo le coordinate x e y come due argomenti separati?
— ბიმო

Risposte:


7

J , 37 34 byte

0<@|:' x'{~((i.@]e.#.~)1+>./) ::#:

Provalo online!

                       1+>./          maximum for each coordinate + 1
             i.@]                     make an array with these dimensions filled with 0..x*y
                                      /* if the input is empty, 
                                         1+>./ is negative infinity
                                         and i.@] throws an error  */
                   #.~                mixed base conversion of input
                 e.                   replace the elements of i.@]
                                        with 1 if it's present in the
                                        converted input, 0 otherwise
           (                ) ::      if there's an error do the other thing instead
                                #:    "to binary", for empty input this returns a 0x0 matrix
0<@|:' x'{~                           index into character string, transpose and put in a box

1
Immagino che la formattazione dell'output sia migliore di quella che ho proposto;)
— racer290,

Perché è ::emptycosì prolisso? Che cosa fa? Perché non può essere semplificato a 1 byte o giù di lì? (Non ho conoscenza di J)
— Magic Octopus Urn,

L'ho eseguito su TIO senza :: vuoto e sembrava funzionare (non conosco neanche J)
— Quintec

In realtà :: vuoto sembra gestire il "" caso di input
— Quintec,

@MagicOctopusUrn Non conosco un modo più breve per produrre un box veramente vuoto, per impostazione predefinita sono alti 1 riga.
— FrownyFrog,

4

JavaScript (ES6), 150 byte

Accetta input come un elenco di coordinate 1 indicizzate in [x,y]formato. Restituisce una stringa.

a=>(g=w=>y<h?' |-+x'[4*a.some(a=>a+''==[x,y])|2*(-~y%h<2)|++x%w<2]+[`
`[x=x<w?x:+!++y]]+g(w):'')((M=i=>Math.max(2,...a.map(a=>a[i]+2)))(x=y=0),h=M(1))

Provalo online!


4

Haskell , 127 123 byte

Questo definisce l'operatore (!)che prende un elenco di coordinate x e un elenco delle coordinate y corrispondenti :

x!y|l<-'+':('-'<$m x)++"+"=unlines$l:['|':[last$' ':['x'|(i,j)`elem`zip x y]|i<-m x]++"|"|j<-m y]++[l];m x=[1..maximum$0:x]

Provalo online!

Ungolfed / Spiegazione

La funzione di supporto si maspetta un elenco e restituisce gli indici (basati su 1) fino al massimo, se l'elenco è vuoto restituisce []:

m x | null x    = []
    | otherwise = [1 .. maximum x]

L'operatore effettivo (!)è solo una comprensione dell'elenco, che attraversa tutte le coordinate e sceglie un carattere o x, a cui si uniscono le nuove linee:

x ! y
  -- construct the top and bottom line
  | l <- "+" ++ replicate (maximum (0:x)) '-' ++ "+"
  -- join the list-comprehension with new-lines
  = unlines $ 
  -- prepend the top line
      [l]
  -- the actual map:
    -- begin the line with | and add the correct chars for each coordinate
      ++ [ "|" ++ [ if (i,j) `elem` zip x y then 'x' else ' '
    -- "loop" over all x-coordinates
                 | i <- m x
                 ]
    -- end the line with a |
           ++ "|"
    -- "loop" over all y-coordinates
         | j <- m y
         ]
  -- append the bottom line
      ++ [l]

3

Tela , 22 byte

ø╶{X;┤╋}l|*eL┤-×+e:└∔∔

Provalo qui!

Accetta input con 1 indice.

Alla fine ho deciso di correggere un bug che mi dava fastidio da anni e ho golfato fino a 21 byte .

Spiegazione (metà ASCII-fied per monospace):

ø╶{X;┤╋}l|*eL┤-×+e:└++  full program, implicitly outputting ToS at the end
ø                       push an empty Canvas - the map
 ╶{    }                for each array in the input array
   X                      push "X"
    ;┤                    and push the two coordinates separately on the stack
      ╋                   and overlap the "X" there in the map
        l               get the vertical length of the map
         |*             repeat "|" vertically that many times
           e            encase the map in two of those vertical bars
            L           get the horizontal length of the map
             ┤          subtract 2 (leave place for the "+"es)
              -×        repeat "-" that many times
                +e      encase that line in "+"es
                  :└    push a copy of that below the map
                    ++  and join the 3 items vertically

3

Python 2 , 151 140 138 byte

-2 byte grazie a Jo King.

L'input è 1 indicizzato.

m=input()
w,h=map(max,zip((0,0),*m))
b=['+'+'-'*w+'+']
M=b+['|'+' '*w+'|']*h+b
for x,y in m:M[y]=M[y][:x]+'x'+M[y][x+1:]
print'\n'.join(M)

Provalo online!


Ho il sospetto che tu stia utilizzando l'indicizzazione basata su 1, ti preghiamo di lasciare una nota nella risposta come indicato nella sfida.
— racer290,

2

Carbone , 37 byte

≔E²⁺²⌈Eθ§λιηB⊟⮌η⊟ηFθ«J⊟⮌ι⊟ιx

Provalo online! Il collegamento è alla versione dettagliata del codice. 1-indicizzati. Spiegazione:

¿¬LθUR²+«

Input vuoto per casi speciali disegnando un rettangolo 2x2 di +s.

≔E²⁺²⌈Eθ§λιη

Trasponi l'input, prendi il massimo di ogni colonna (ora riga) e aggiungi 2 per ottenere la dimensione della scatola nelle coordinate del carbone.

B⊟⮌η⊟η

Disegna la scatola.

Fθ«

Passa sopra ogni coordinata.

J⊟⮌ι⊟ι

Vai alla sua posizione.

x

Segna con una croce.


Sembra fallire per input vuoto: tio.run/…
— wastl

@wastl Grazie, ho escogitato una soluzione alternativa.
— Neil,

2

Stax , 32 31 24 byte

╩╠ee%╙æM■↓^⌐╧ΩΓ¡c¥èf¢○ [

Esegui ed esegui il debug

Prende indici basati su 0 come array di [y, x]coppie.

Spiegazione:

zs'X&|<cM%'-*'+|S]s{'||Smn++m Unpacked program, implicit input
zs                            Tuck empty array under input
  'X                          Push "X"
    &                         Assign element at all indices (create map)
                                As the indexing arrays are an array of arrays, treat them as a path to navigate a multidimensional array.
                                Extend array if needed.
     |<                       Left-align all to the length of the longest.
       cM%                    Copy, transpose, length (width)
          '-*                 Repeat "-"
             '+|S             Surround with "+"
                 ]s           Make a singleton and tuck it below the map
                   {    m     Map:
                    '||S        Surround with "|"
                         n++  Surround with the above/below border (built above)
                            m Map:
                                Implicit output

1
Ben fatto. È possibile ottenere un po 'più di chilometraggio dall'istruzione |Ssurround e una mappa abbreviata finale. ( m) Surround prende ae bdalla pila e produce b+a+b. E puoi usare al mposto del finale |Jper scorrere le righe e produrre output. Ad esempio
— ricorsivo

1
Ancora una cosa: puoi sostituirla z]n+H%con cM%. Questo è il pezzo che ottiene la larghezza della mappa, ma ha un caso speciale per le mappe vuote. Se trasponi la mappa prima di misurarla, il caso speciale scompare.
— ricorsivo

@recursive Stavo cercando qualcosa come surround, ma ho cercato le parole chiave sbagliate
— wastl

Come chiameresti naturalmente quell'operazione? Potrei aggiungerlo ai documenti in modo che la prossima persona possa trovarlo.
— ricorsivo

@recursive Non ricordo cosa fosse, e lo chiamerei naturalmente surround ora
— wastl

2

R , 133 125 122 byte

function(m)cat(z<-c("+",rep("-",u<-max(m[,1])),"+","
"),rbind("|",`[<-`(matrix(" ",u,max(m[,2])),m,"x"),"|","
"),z,sep="")

Provalo online!

1-indicizzati. Prende una matrice come argomento. Risparmiato 8 byte grazie a digEmAll, 3 grazie a Giuseppe! Spiegazione (versione precedente del codice):

function(m){                           #x and y are the 1st and 2nd col of m
s=matrix(32,u<-max(m[,1]),max(m[,2]))  #s (treasure map) has dim max(x), max(y) 
s[m]=120                               #place the X's on the map
cat(                                   #print:
    z<-c("+",rep("-",u),"+","\n"),     #the top line
    intToUtf8(rbind(124,s,124,13)),    #the map
    z,                                 #the bottom line.
    sep="")
}

Se usi caratteri normali invece di codici utf8 risparmi 8 caratteri: tio.run/##ZU7NDoIwDL7zFEu9tKEzDONF4UkMhzmGchgYNhKC@uwIaozRpG36/…
— digEmAll

122 byte utilizzando [<-direttamente per rimuovere le parentesi graffe.
— Giuseppe

@Giuseppe davvero! Sapevo che doveva esserci un modo.
— JayCe

1

coords presi nel formato [y, x]

JavaScript (Node.js) , 191 184 byte

c=f=a=>{a.map(([y,x])=>(c[M<++y?M=y:y]=c[y]||[])[m<++x?m=x:x]="x",M=m=0)
m++
M++
s=""
for(i=0;i<=M;s+=`
`,i++)for(j=0;j<=m;j++)s+=(c[i]||0)[j]||(j%m?i%M?" ":"-":i%M?"|":"+") 
return s}

Provalo online!


Penso che tu abbia scambiato per sbaglio le coordinate x e y da qualche parte ..
— racer290,

@ racer290 potresti essere più specifico?
— DanielIndie,

Cercando la tua soluzione, ho scoperto che cambiare la coordinata x nei casi di test ha portato a un cambiamento nella direzione verticale della coordinata. Suppongo che il bug sia nella prima riga ( a.map(([y,x]))
— racer290,

ma x è il parametro giusto come si può vedere dai casi di test
— DanielIndie,

2
Quindi nella tua soluzione prendi prima le coordinate y? Penso che sarebbe meglio lasciare una nota su questo nella tua risposta allora.
— racer290,

1

JavaScript, 180 byte

F = 

s=>s.map(([x,y])=>(t[y]=t[Y<y?Y=y:y]||[])[X<x?X=x:x]='x',t=[X=Y=0])&&[...t,0].map((_,y)=>[...Array(X+2)].map((_,x)=>[(t[y]||0)[x]||' ',...'-|+'][!(y%~Y)+2*!(x%~X)]).join``).join`
`


console.log(F([[1,11],[6,6],[11,1]]))


1

Java 10, 238 223 byte

c->{var r="";int w=0,h=0,x,y;for(var l:c){w=(x=l.get(0))>w?x:w;h=(y=l.get(1))>h?y:h;}for(w++,h++,x=-1;++x<=w;r+="\n")for(y=-1;++y<=h;)r+=x%w+y%h<1?"+":x%w<1?"-":y%h<1?"|":(c+"").contains("["+x+", "+y+"]")?"x":" ";return r;}

Coordinate 1-indicizzate.

Provalo online.

Spiegazione:

c->{                      // Method with 2D Lists as parameter and String return-type
  var r="";               //  Result-String, starting empty
  int w=0,h=0,            //  Width and height, starting at 0
      x,y;                //  Temp x,y coordinates
  for(var l:c){           //  Loop over the Inner Lists containing the coordinates
    w=(x=l.get(0))>w?x:w; //   Determine width based on max x-coordinate
    h=(y=l.get(1))>h?y:h;}//   Determine height based on max y-coordinate
  for(w++,h++,            //  Increase both the width and height by 1
      x=-1;++x<=w;        //  Loop `x` in the range [0, width]
      r+="\n")            //    After every iteration: append a new-line to the result
    for(y=-1;++y<=h;)     //   Inner loop `y` in the range [0, height]
      r+=                 //    Append the following character to the result-String:
        x%w+y%h<1?        //    If it's one of the corners:
          "+"             //     Append "+"
        :x%w<1?           //    Else-if it's the top or bottom row:
          "-"             //     Append "-"
        :y%h<1?           //    Else-if it's the right or left column:
          "|"             //     Append "|"
        :(c+"").contains("["+x+", "+y+"]")? 
                          //    Else-if the current `x,y` is part of the input-coordinates
          "x"             //     Append "x"
        :                 //    Else:
          " ";            //     Append " "
  return r;}              //  Return the result-String

rwhxy; lcwxlgetw? XW; hylgeth? YH; forwhxxwr. foryyhrxwyh? xwyhcxy? xr.
— Magic Octopus Urn,

@MagicOctopusUrn Cosa stai nominando tutte le variabili e get/ forper? : S XD
— Kevin Cruijssen,

1

C (gcc) , 246 234 byte

Grazie a ceilingcat per il suggerimento.

Zero indicizzati. La funzione prende un elenco di coordinate e buffer, trova i valori massimi xey, riempie il buffer di spazi, genera il frame e quindi traccia le "x".

f(int*a,char*c){int*b=a,x,y=x=-1,i=0;for(;~*b;*++b>y?y=*b:0,++b)*b>x?x=*b:0;for(x+=4,y+=3,memset(c,32,x*y);++i<x;c[i]=c[y*x-i]=45);for(i=0;i<y;c[x*++i-1]=10*(i<=y))c[x*i]=c[x*i+x-2]=i&&y/i?124:43;for(b=a;~*b;b+=2)c[*b+1-~b[1]*x]='x';}

Provalo online!



1

05AB1E , 44 42 byte

ζεZ}>`UX'-×'+.ø©,F'|NVXF¹YN‚.å„ xè}'|J,}®,

Provalo online!


 ζεZ}>`                                     # Push the max of X and Y to the stack +1.
       UX                                   # Store the max X.
         '-×'+.ø©,                          # Print the top border.
                  F                     }   # From 0 to Y...
                   '|                       # Push left border.
                     NV                     # Store current Y in Y.
                       XF          }        # From 0 to X...
                         ¹                  # Push input.
                          YN‚               # Group current X and Y.
                             .å             # Exists in original input ? 1 : 0
                               „ xè         # Exists ? 'X' : ' '
                                    '|J,    # Right border, join, print.
                                         ®, # Print bottom border.

X e Y potrebbero essere invertiti, non sapevo se ciò avesse importanza.


Penso di averlo in meno byte, ma vedremo ... No.

ζεZ}>`D'-×'+.øUð×'|.øs.D)X.ø©svy>`s®sUXès'xsǝXǝ}

1
Non è molto, ma puoi salvare 1 byte modificando il primo Fin Lv, rimuovendolo NVe modificandolo Yin y. 41 byte
— Kevin Cruijssen,

1
Come menzionato da @Emigna nella chat , εZ}può essere €à.
— Kevin Cruijssen,

Odio la modifica di questo sul cellulare attenderà fino al prossimo pc.
— Magia Octopus Urna

1
@KevinCruijssen Ývno Lv, ma comunque una buona modifica :).
— Magic Octopus Urn,

Ah, hai ragione. Ývinvece di Lv. Colpa mia.
— Kevin Cruijssen,

0

C (gcc) , 229 220 216 byte

-9 byte grazie a ceilingcat .

Zero indicizzati. Prende le coordinate come elenco di numeri, dove i numeri pari sono X e i numeri dispari sono Y.

X,Y,i,j,k,x,z;f(l,n)int*l;{for(X=Y=0,i=n*=2;i--;X=fmax(l[i],X))Y=fmax(l[i--],Y);n&&X++-Y++;for(--i;i++<Y;puts(""))for(j=-1;j<=X;z=i<0|i==Y,putchar(j++<0|j>X?z?43:'|':x?z?45:32:'x'))for(x=k=n;k--;)x*=l[k--]-i|l[k]-j;}

Provalo online!


@ceilingcat Cheers!
— Gastropner,

Suggerisci for(n&&X++-Y++;i<=Y;i+=puts(""))invece din&&X++-Y++;for(--i;i++<Y;puts(""))
— ceilingcat
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.