Cambia segno, loop e display con imbottitura minima


17

Ingresso:

Due numeri interi: uno negativo, uno positivo.

Produzione:

Sulla prima riga output dal più basso al più alto. Nella seconda riga abbiamo rimosso i numeri più alti e più bassi e abbiamo cambiato il segno di tutti i singoli numeri. Sulla terza riga abbiamo rimosso di nuovo i numeri più alti e più bassi e cambiato di nuovo il segno con tutti i singoli numeri. ecc. (L'esempio che segue dovrebbe rendere più chiara la sfida.)

Importante: inoltre, aggiungiamo spazi in modo che i numeri in una colonna siano tutti allineati (a destra).
L'allineamento minimo è la parte principale di questa sfida, questo significa che non puoi semplicemente rendere ogni singolo numero della stessa larghezza. La larghezza di una colonna si basa sulla larghezza numerica più grande di quella colonna specifica (e la sequenza con cambio di segno è di dare ai numeri una varietà di larghezza per colonna).


Per esempio:

Input: -3,6

Output:
-3,-2,-1, 0, 1, 2, 3, 4,5,6   // sequence from lowest to highest
 2, 1, 0,-1,-2,-3,-4,-5       // -3 and 6 removed; then all signs changed
-1, 0, 1, 2, 3, 4             // 2 and -5 removed; then all signs changed again
 0,-1,-2,-3                   // -1 and 4 removed; then all signs changed again
 1, 2                         // 0 and -3 removed; then all signs changed again
                              // only two numbers left, so we're done

Come puoi vedere sopra, gli spazi vengono aggiunti ai numeri positivi, quando condividono una colonna con numeri negativi per compensare il -(lo stesso vale per i numeri a 2 cifre).

Regole della sfida:

  • L'input deve essere di due numeri interi
    • Puoi presumere che questi numeri interi siano compresi nell'intervallo -99- 99(inclusivo).
    • Il primo numero intero sarà negativo e l'altro sarà positivo.
  • L'output può essere in qualsiasi formato ragionevole, purché sia ​​chiaro che ci sono righe e colonne allineate correttamente: vale a dire STDOUT; ritornando come stringa con newline; ritorno come elenco di stringhe; ecc. La tua chiamata.
  • L'output deve contenere anche un delimitatore di tua scelta (ad eccezione di spazi, tabulazioni, nuove righe, cifre o -): Ie ,; e ;e |; e X; ecc. sono tutti delimitatori accettabili.
  • Le righe di output potrebbero non contenere un delimitatore iniziale o finale.
  • L'output può contenere UNA nuova riga finale e qualsiasi riga può contenere un numero qualsiasi di spazi finali.

Regole generali:

  • Questo è , quindi vince la risposta più breve in byte.
    Non lasciare che le lingue di code-golf ti scoraggino dal pubblicare risposte con lingue non codegolfing. Prova a trovare una risposta il più breve possibile per "qualsiasi" linguaggio di programmazione.
  • Per la tua risposta valgono regole standard , quindi puoi usare STDIN / STDOUT, funzioni / metodo con i parametri corretti, programmi completi. La tua chiamata.
  • Scappatoie predefiniteSono vietate le .
  • Se possibile, aggiungi un link con un test per il tuo codice.
  • Inoltre, si prega di aggiungere una spiegazione, se necessario.

Casi test:

Input: -3,6

Output:
-3,-2,-1, 0, 1, 2, 3, 4,5,6
 2, 1, 0,-1,-2,-3,-4,-5
-1, 0, 1, 2, 3, 4
 0,-1,-2,-3
 1, 2

Input: -1,1

Output:
-1,0,1
 0

Input: -2,8

Output:
-2,-1, 0, 1, 2, 3, 4, 5, 6,7,8
 1, 0,-1,-2,-3,-4,-5,-6,-7
 0, 1, 2, 3, 4, 5, 6
-1,-2,-3,-4,-5
 2, 3, 4
-3

Input: -15,8

Output: 
-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6,7,8
 14, 13, 12, 11, 10,  9, 8, 7, 6, 5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7
-13,-12,-11,-10, -9, -8,-7,-6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6
 12, 11, 10,  9,  8,  7, 6, 5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5
-11,-10, -9, -8, -7, -6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4
 10,  9,  8,  7,  6,  5, 4, 3, 2, 1, 0,-1,-2,-3
 -9, -8, -7, -6, -5, -4,-3,-2,-1, 0, 1, 2
  8,  7,  6,  5,  4,  3, 2, 1, 0,-1
 -7, -6, -5, -4, -3, -2,-1, 0
  6,  5,  4,  3,  2,  1
 -5, -4, -3, -2
  4,  3

Input: -3,15

Output:
-3,-2,-1, 0, 1, 2, 3, 4,  5, 6,  7,  8,  9, 10, 11, 12, 13,14,15
 2, 1, 0,-1,-2,-3,-4,-5, -6,-7, -8, -9,-10,-11,-12,-13,-14
-1, 0, 1, 2, 3, 4, 5, 6,  7, 8,  9, 10, 11, 12, 13
 0,-1,-2,-3,-4,-5,-6,-7, -8,-9,-10,-11,-12
 1, 2, 3, 4, 5, 6, 7, 8,  9,10, 11
-2,-3,-4,-5,-6,-7,-8,-9,-10
 3, 4, 5, 6, 7, 8, 9
-4,-5,-6,-7,-8
 5, 6, 7
-6

Input: -12,12

Output:
-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8,  9, 10,11,12
 11, 10,  9, 8, 7, 6, 5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11
-10, -9, -8,-7,-6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10
  9,  8,  7, 6, 5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7,-8,-9
 -8, -7, -6,-5,-4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8
  7,  6,  5, 4, 3, 2, 1, 0,-1,-2,-3,-4,-5,-6,-7
 -6, -5, -4,-3,-2,-1, 0, 1, 2, 3, 4, 5, 6
  5,  4,  3, 2, 1, 0,-1,-2,-3,-4,-5
 -4, -3, -2,-1, 0, 1, 2, 3, 4
  3,  2,  1, 0,-1,-2,-3
 -2, -1,  0, 1, 2
  1,  0, -1
  0

1
"Mai al di fuori di -100-100" include anche non essere mai -100 o 100?
Jonathan Allan,

@JonathanAllan Penso di sì. Ha senso escludere -100 e 100, perché se fossero inclusi, verrà aggiunta una terza / quarta cifra e tutto cambierebbe per soli 2 valori
Mr. Xcoder

Relazionato. (Un'altra sfida in cui il riempimento e l'allineamento a destra di una griglia è il componente principale.)
Martin Ender

1
@JonathanAllan Ho cambiato un po 'le parole. Si può presumere che sia l'input negativo più piccolo possibile -99e sia l'input positivo più grande possibile 99.
Kevin Cruijssen,

1
Caso di prova proposto: -3,15. Alcune risposte non funzionano correttamente.
Betseg,

Risposte:


7

Gelatina , 25 24 20 byte

rµḊṖNµÐĿZbȷG€Ỵ€Zj€”,

Questo è un collegamento diadico che restituisce una matrice di righe.

Provalo online!

Come funziona

rµḊṖNµÐĿZbȷG€Ỵ€Zj€”,  Dyadic link. Arguments: a, b

r                      Range; yield [a, ..., b].
 µ   µÐĿ               Apply the enclosed chain until the results are no longer
                       unique. Return the array of results.
  Ḋ                      Dequeue; remove the first item.
   Ṗ                     Pop; remove the last item.
    N                    Negate; multiply all remaining integers by -1.
       Z               Zip; transpose rows and columns.
        bȷ             Base 1000; map each n to [n].
          G€           Grid each; in each row, pad all integers to the same length,
                       separating the (singleton) rows by linefeeds.
            Ỵ€         Split each result at linefeeds.
              Z        Zip to restore the original layout.
               j€”,    Join each row, separating by commata.

7

05AB1E , 59 byte

Ancora una volta sono fregato dallo stesso bug che ho scritto una correzione per mesi fa ma non ho mai spinto ... Il
golf dovrebbe essere comunque possibile.

Ÿ[Ðg1‹#ˆ¦(¨]\\¯vy€g}})J.Bvyð0:S})øvyZs\})U¯vyvyXNèyg-ú}',ý,

Provalo online!


Mi sono avvicinato abbastanza a questo: ŸÐ',ý,gÍ;µ¦¨(D',ý,¼non si adatta perfettamente alle specifiche di formattazione, vedi se riesci a migliorarlo;)
Okx

1
@Okx: Sì, la formattazione è sicuramente la parte difficile qui. Qualcosa del genere Ÿ[Ðg1‹#',ý,¦(¨sarebbe abbastanza altrimenti :)
Emigna

1
Non funziona correttamente per input come -3,15.
Betseg,

@betseg: proprio così. Ripristinato alla vecchia versione.
Emigna

7

Java 8, 483 480 486 467 byte

(a,b)->{int f=0,l=b-a+3,z[][]=new int[l][l],y[]=new int[l],i,j,k=0;for(;b-a>=0;k++,a++,b--,f^=1)for(j=0,i=a;i<=b;i++)z[k][j++]=f<1?i:-i;String r="",s;for(i=0;i<l;y[i++]=k)for(j=0,k=1;j<l;k=f>k?f:k)f=(r+z[j++][i]).length();for(i=0;i<l;i++){k=z[i][0];if(i>0&&k==z[i][1]&k==z[i-1][2])break;for(j=0;j<l;){k=z[i][j];s="";for(f=(s+k).length();f++<y[j];s+=" ");f=z[i][++j];if(k==f){r+=(i>0&&z[i-1][1]==z[i][1]?s+0:"")+"\n";j=l;}else r+=s+k+(f==z[i][j+1]?"":",");}}return r;}

Byte generati a causa di bug-fix.

Ok, ci è voluto MOLTO più tempo (e byte) di quanto pensassi (in Java che è ..). Questo può sicuramente essere risolto un po 'di più, probabilmente usando un approccio completamente diverso invece di creare un array di griglie NxN per riempire e quindi "eliminare" gli zeri (con un fastidioso caso limite per il test-case -1,1, così come-12,12 ) .

Provalo online.

Spiegazione:

(a,b)->{        // Method with two integer parameters and String return-type
  int f=0,      //  Flag-integer, starting at 0
      l=b-a+3,  //  Size of the NxN matrix,
                //  plus two additional zeros (so we won't go OutOfBounds)
      z[][]=new int[l][l],
                //  Integer-matrix (default filled with zeros)
      y[] = new int[l],
                //  Temp integer-array to store the largest length per column
      i,j,k=0;  //  Index-integers
  for(;b-a>=0   //  Loop as long as `b-a` is not negative yet
      ;         //    After every iteration:
       k++,     //     Increase `k` by 1
       a++,     //     Increase `a` by 1
       b--,     //     Decrease `b` by 1
       f^=1)    //     Toggle the flag-integer `f` (0→1 or 1→0)
    for(j=0,i=a;i<=b;i++)
                //   Inner loop `i` in the range [`a`, `b`]
      z[k][j++]=//    Set all the values in the matrix to:
        f<1?    //     If the flag is 0:
         i      //      Simply use `i`
        :       //     Else (flag is 1):
         -i;    //      Use the negative form of `i` instead
  String r="",  //  The return-String
         s;     //  Temp-String used for the spaces
  for(i=0;i<l;  //  Loop `i` over the rows of the matrix
      ;y[i++]=k)//    After every iteration: Set the max column-width
    for(j=0,k=1;j<l;
                //   Inner loop `j` over the cells of each row
        k=f>k?f:k)
                //     After every iteration: Set `k` to the highest of `k` and `f`
      f=(r+z[j++][i]).length();
                //    Determine current number's width
                //    (NOTE: `f` is no longer the flag, so we re-use it as temp value)
  for(i=0;i<l;i++){
                //  Loop `i` over the rows of the matrix again
    k=z[i][0];  //   Set `k` to the first number of this row
    if(i>0      //   If this isn't the first row
       &&k==z[i][1]&k==z[i-1][2])
                //   and the first number of this row, second number of this row,
                //   AND third number of the previous row all equal (all three are 0)
      break;    //    Stop loop `i`
    for(j=0;j<l;){
                //   Inner loop `j` over the cells of each row
      k=z[i][j];//    Set `k` to the number of the current cell
      s="";     //    Make String `s` empty again
      for(f=(s+k).length();f++<y[j];s+=" ");
                //    Append the correct amount of spaces to `s`,
                //    based on the maximum width of this column, and the current number
      f=z[i][++j];
                //    Go to the next cell, and set `f` to it's value
      if(k==f){ //    If the current number `k` equals the next number `f` (both are 0)
        r+=     //     Append result-String `r` with:
          (i>0  //      If this isn't the first row
           &&z[i-1][1]==z[i][1]?
                //      and the second number of this and the previous rows 
                //      are the same (both are 0):
            s+0 //       Append the appropriate amount of spaces and a '0'
           :    //      Else:
            "") //       Leave `r` the same
          +"\n";//     And append a new-line
         j=l;}  //     And then stop the inner loop `j`
      else      //    Else:
       r+=s     //     Append result-String `r` with the appropriate amount of spaces
          +k    //     and the number 
          +(f==z[i][j+1]?"":",");}}
                //     and a comma if it's not the last number of the row
  return r;}    //  Return the result `r`

6

Javascript (ES6), 269 byte

(a,b,d=~a+b+2,o=Array(~~(d/2)+1).fill([...Array(d)].map(_=>a++)).map((e,i)=>e.slice(i,-i||a.a)).map((e,i)=>i%2==0?e:e.map(e=>e*-1)))=>o.map(e=>e.map((e,i)=>' '.repeat(Math.max(...[...o.map(e=>e[i]).filter(e=>e!=a.a)].map(e=>[...e+''].length))-`${e}`.length)+e)).join`
`

Ha spiegato:

(                                     // begin arrow function

  a,b,                                // input

  d=~a+b+2,                           // distance from a to b

  o=Array(~~(d/2)+1)                  // create an outer array of
                                      // (distance divided by 2 
                                      // floored + 1) length

    .fill(                            // fill each outer element
                                      // with the following:

      [...Array(d)]                   // create inner array of the 
                                      // distance length and 
                                      // fill with undefined

        .map(_=>a++)                  // map each inner element 
                                      // iterating from a to b
    ) 
    .map(                             // map outer array

      (e,i)=>e.slice(i,-i||a.a)       // remove n elements from each end 
                                      // of the inner array corresponding 
                                      // to the outer index with a special 
                                      // case of changing 0 to undefined
    )
    .map(                             // map outer array

      (e,i)=>i%2==0?e:e.map(e=>e*-1)  // sign change the inner elements
                                      // in every other outer element
    )
)=>                                   // arrow function return

  o                                   // outer array

    .map(                             // map outer array

      e=>e.map(                       // map each inner array

        (e,i)=>' '.repeat(            // repeat space character the
                                      // following amount:

          Math.max(...                // spread the following array to
                                      // max arguments:

            [...                      // spread the following to an
                                      // array:

              o                       // outer array

                .map(e=>e[i])         // map returning each element of
                                      // the same inner index from the
                                      // outer array

                .filter(e=>e!=a.a)    // remove undefined elements
            ]
            .map(e=>[...e+''].length) // map each element to the  
                                      // length of the string

          )                           // returns the max string 
                                      // length of each column

          -`${e}`.length              // subtract the current 
                                      // element's string length 
                                      // from the max string length

      )                               // returns the appropriate amount
                                      // of padding

      +e                              // add the element to the padding
    )
  ).join`
`                                     // join each element of outer
                                      // array as string with newline

const f = (a,b,d=~a+b+2,o=Array(~~(d/2)+1).fill([...Array(d)].map(_=>a++)).map((e,i)=>e.slice(i,-i||a.a)).map((e,i)=>i%2==0?e:e.map(e=>e*-1)))=>o.map(e=>e.map((e,i)=>' '.repeat(Math.max(...[...o.map(e=>e[i]).filter(e=>e!=a.a)].map(e=>[...e+''].length))-`${e}`.length)+e)).join`
`
console.log('Test Case: -1,1')
console.log(f(-1,1))
console.log('Test Case: -3,6')
console.log(f(-3,6))
console.log('Test Case: -2,8')
console.log(f(-2,8))
console.log('Test Case: -15,8')
console.log(f(-15,8))
console.log('Test Case: -3,15')
console.log(f(-3,15))
console.log('Test Case: -12,12')
console.log(f(-12,12))


Puoi aggiungere i nuovi casi di test?
Bet

4

QBIC , 46 byte

::[0,-1*a+b,2|[a,b|?d*q';`]q=q*-1┘a=a+1┘b=b-1?

Come funziona:

::           Read the negative and positive ints as a and b
[0,-1*a+b,2| FOR(c = 0; c < range(a, b); c+=2) {} This creates the proper amount of lines.
  [a,b|      For each line, loop from lower to upper
    ?d*q     Print the current point in the range, accounting for the sign-switch
     ';`     And suppress newlines. The ' and ` stops interpreting special QBIC commands.
  ]          NEXT line
  q=q*-1┘    Between the lines, flip the sign-flipper
  a=a+1┘     Increase the lower bound
  b=b-1?     Decrease the upper bound, print a newline
             The outermost FOR loop is auto-closed at EOF.

Fortunatamente, quando si stampa un numero, QBasic aggiunge automaticamente l'imbottitura necessaria.


Un altro caso di trovare la lingua giusta per fare il lavoro :) +1
ElPedro

+1 È disponibile un compilatore online per QBIC? Mi piacerebbe vederlo in azione per tutti i casi di test (anche se presumo che allinea automaticamente tutto). La prima volta che visualizzo QBIC, quindi due domande quando leggo la tua spiegazione: se l'ho letto correttamente q, il valore predefinito inizia da 1? Tutti i valori in QBIC iniziano da 1 o c'è qualcosa che mi manca qui? E qual è il d/ dove dsta per? Oppure dil numero corrente nel ciclo e il ?semplice sono delimitati nel codice del ciclo ?continuo (invece di essere il numero corrente, come è stato inizialmente letto)?
Kevin Cruijssen,

1
@KevinCruijssen Nessun interprete online ancora, scusa. Sto lavorando su uno, ma è più difficile di quanto pensi a far funzionare QBasic 4.5 nel tuo browser :-). qinizia da 1. Tutte le lettere minuscole sono numerate e le lettere q-zsono inizializzate su 1-10. E diversi comandi assegnano automaticamente i numeri nell'ordine in cui si trovano nel codice. dè in effetti l'iteratore sul ciclo FOR interno. Per maggiori dettagli, vedi anche la vetrina - o questo
steenbergh

3

Perl 6 , 146 byte

{$_:=(($^a..$^b).List,{-«.[1..*-2]}...3>*).List;$/:=[map {"%{.max}s"},roundrobin($_)».chars];map {join ',',map {$^a.fmt: $^b},flat($_ Z $/)},$_}

Provalo

Produce una sequenza di stringhe

Allargato:

{  # bare block lambda with placeholder parameters 「$a」 and 「$b」

  # generate the data
  $_ := (                 # bind to $_ so it isn't itemized

                          # produce a sequence
    ( $^a .. $^b ).List,  # seed the sequence, and declare parameters
    { \ .[ 1 .. *-2 ] } # get all the values except the ends and negate
    ...                   # keep producing until
    3 > *                 # the length of the produced list is less than 3

  ).List;                 # turn the Seq into a List


  # generate the fmt arguments
  $/ := [                 # bind an array to 「$/」 so it isn't a Seq
    map
      { "%{ .max }s" },   # turn into a 「.fmt」 argument ("%2s")

      roundrobin($_)\     # turn the "matrix" 90 degrees
      ».chars             # get the string length of each number
  ];


  # combine them together
  map
    {
      join ',',
        map
          { $^a.fmt: $^b }, # pad each value out
          flat(
            $_ Z $/         # zip the individual number and it's associated fmt
          )
    },
    $_                      # map over the data generated earlier
}

3

PHP 7.1, 277 byte

for([,$a,$b]=$argv,$c=count($r=range($a,$b))/2;$c-->0;$r=range(-$r[1],-$r[count($r)-2]))$y[]=array_map(strlen,$x[]=$r);for($i=0;$i<count($y[0]);$i++)$z[$i]=max(array_column($y,$i));foreach($x as $g){$o=[];foreach($g as$k=>$v)$o[]=sprintf("%$z[$k]d",$v);echo join(",",$o)."\n";}

Interprete online


2
Puoi collegare un interprete online?
Bet

@betseg Fatto e realizzato che la mia versione non aveva funzionato correttamente
Jörg Hülsermann

oh Dio, sto usando php su codegolf.se. HANNO TUTTI I UPVOTES.
Evan Carroll

3

Applicazione console C # 196 byte

static void p(int a,int b){string S="",d ="";int c=-1;for(int i=b;i >=a;i--){c=c==1?c=-1:c=1;for(int j = a;j<=i;j++){S=j!=a?",":S="";d=d+S+(j*c);}d+= "\r\n";a++;}Console.Write(d);Console.Read();}

Benvenuti in PPCG! Puoi indentare il tuo codice usando 4 spazi (vedi la mia modifica). Nel golf del codice, devi avere il conteggio dei byte più breve (la quantità di byte nel tuo codice) possibile - ciò significa nomi di variabili più brevi e rimozione di spazi. Inoltre, una volta terminato, dovresti inserire il numero di byte nell'intestazione.
clismique,

2

Javascript - 196 185 176 byte

function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}l.shift();l.pop()}return h}

Non sono davvero al passo con alcune delle più recenti tecniche JS, quindi questo potrebbe probabilmente essere giocato a golf molto di più.

Crea semplicemente una buona tabella HTML vecchio stile senza larghezza definita per le celle, quindi la prima riga viene impostata automaticamente sulla larghezza di ogni spaziatura con una spaziatura ottimale. Inoltre (ab) utilizza la "funzione" HTML di non richiedere tag di chiusura se arriva prima un nuovo tag di apertura.

<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}l.shift();l.pop()}return h}
document.write(f(-1,1))
</script>

<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}l.shift();l.pop()}return h}
document.write(f(-3,6))
</script>

<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}h+='</tr>';l.shift();l.pop()}return h}
document.write(f(-2,8))
</script>

<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}h+='</tr>';l.shift();l.pop()}return h}
document.write(f(-15,8))
</script>

<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}h+='</tr>';l.shift();l.pop()}return h}
document.write(f(-3,15))
</script>

<script>
function f(i,j){l=[];for(x=i;x<j+1;x++)l.push(x);h='<table>';while(l.length>0){h+='<tr>';for(x=0;x<l.length;x++){h+='<td align=right>'+l[x];l[x]*=-1}h+='</tr>';l.shift();l.pop()}return h}
document.write(f(-12,12))
</script>


2

Python 2 - 208 byte

Provalo online

d,u=input()
l=[x for x in range(d,u+1)]
M=map(lambda x:~9<x<21-u-u%2and 2or 3,l)
M[-1]-=1
M[-2]-=1
while len(l)>0:print','.join(map(lambda i:('%'+'%d'%M[i]+'d')%l[i],range(len(l))));l=map(lambda e:-e,l[1:-1])

Crea una matrice di valori di riempimento e quindi lo utilizza per costruire stringhe formattate necessarie

Spiegazione:

d,u=input()
# create list of all values
l=[x for x in range(d,u+1)]
# create array of padding values
# by default, padding 2 used for numbers in [-9;9] and 3 for all other (limited with -99 and 99)
# but contracting list moves numbers larger that 9 under ones, that are <=9
# so upper limit of padding 2 is limited with 21-u-u%2
# (~9 == -10)
M=map(lambda x:~9<x<21-u-u%2and 2or 3,l)
# last two elements should have lower padding as there won't be any other numbers it their columns
M[-1]-=1
M[-2]-=1
while len(l)>0:
    # create formatted string for every element in l
    # join all strings with comma
    print','.join(map(lambda i:('%'+'%d'%M[i]+'d')%l[i],range(len(l))))
    # get slice without first and last element and change sigh
    l=map(lambda e:-e,l[1:-1])

Ciao, benvenuto in PPCG! Sfortunatamente, al momento non è corretto. Hai aggiunto lo stesso margine a tutti i numeri e hai aggiunto spazi come delimitatore. La sfida era usare un delimitatore di tua scelta (tranne gli spazi bianchi), ma ancora più importante: avere l'allineamento basato sul numero con la larghezza maggiore in quella specifica colonna. Consultare la sezione Importante della sfida, nonché i casi di test come esempio. Non sei il primo a farlo in modo errato, ma al momento non è valido con la sfida specificata. Sentiti libero di cancellare, modificare per rispettare le regole e ripristinare la tua risposta
Kevin Cruijssen

2
@KevinCruijssen Grazie per aver segnalato questo! Ho aggiornato la mia risposta
Dead Possum

1
Sembra davvero molto meglio! Solo una piccola regola che hai dimenticato: " L'output può contenere anche un delimitatore di tua scelta (ad eccezione di spazi bianchi e nuove righe) : vale a dire ,e ;e |sono tutti delimitatori accettabili. " Attualmente usi uno spazio come delimitatore. Ma la principale difficoltà della larghezza è stata effettivamente affrontata, quindi finora stai andando alla grande! Solo questo piccolo cambiamento, e quindi dovrebbe essere fatto. :)
Kevin Cruijssen,

1
Perfetto! +1 Ottimo lavoro per correggere tutto. E ancora una volta benvenuto in PPCG. (A proposito, lo spazio è qui: %l[i], rangeobbligatorio?)
Kevin Cruijssen,

2
@KevinCruijssen Spero di rimanere in giro per PPCG per un po ', sembra molto interessante (no, salvato un altro byte)
Dead Possum
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.