Crea un segno di percentuale


24

Dato un numero intero n ≥ 1, genera una rappresentazione 2D di un segno percentuale di larghezza n . La costruzione è la seguente:

  1. Crea una matrice n per n (o elenco di elenchi) riempito con zero.
  2. Inserire quelli negli angoli in alto a sinistra e in basso a destra.
  3. Metti quelli sulla diagonale da in basso a sinistra a in alto a destra.

Per input n = 4, questa costruzione sarebbe simile a:

1. 4x4 matrix of 0s
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
2. 1s in TL and BR corners
1 0 0 0
0 0 0 0
0 0 0 0
0 0 0 1
3. 1s across BL-TR diagonal
1 0 0 1
0 0 1 0
0 1 0 0
1 0 0 1

Questo è un , quindi vince il programma più breve in byte.

Uso una matrice di 1 e 0, ma è anche accettabile usare una stringa di caratteri e spazi non bianchi. Quindi, l'esempio sopra potrebbe apparire come:

#  #
  # 
 #  
#  #

o

#     #
    #
  # 
#     #

Casi test

n
output

1
1

2
1 1
1 1

3
1 0 1
0 1 0
1 0 1

4
1 0 0 1
0 0 1 0
0 1 0 0
1 0 0 1

10
1 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 1

Nota finale

L'aggiunta di una spiegazione sarebbe molto apprezzata.


Le nostre soluzioni possono essere indicizzate 0?
Kritixi Lithos,

5
@Cowsquack Direi di no. Stai ricevendo la larghezza, non un indice.
Conor O'Brien,

Possiamo produrre un elenco di elenchi?
xnor

@xnor Sì; elenco di elenchi e matrice sono sinonimi nel mio post. Lo aggiungerò alla domanda
Conor O'Brien,

Si noti che questo è '1'+'0'*(n-2)con spazi bianchi inseriti
CalculatorFeline

Risposte:


8

Gelatina , 6 byte

²Rm’Ṭs

Provalo online!

Come funziona

²Rm’Ṭs  Main link. Argument: n

²       Square; yield n².
 R      Range; yield [1, ..., n²].
   ’    Decrement; yield n-1.
  m     Modular; yield every (n-1)-th element of the range, staring with the first.
    Ṭ   Untruth; yield a Boolean array with 1's at the specified indices.
     s  Split the resulting array into chunks of length n, creating a matrix.

Inoltre, ²Ḷ%’¬soppure+þ%’=2
ETHproductions,

²Ḷọ’sè così vicino ...
Dennis il

Se solo ci fosse un link a 1 byte "x è divisibile per y" ...
ETHproductions

@ETHproductions C'è ḍ@ma sono due byte.
Erik the Outgolfer,

E ho pensato di essere intelligente con ⁼þµ+1¦Ṫṁ³UG... fino a quando non è ²spuntata una soluzione di Dennis .
Erik the Outgolfer,

11

JavaScript (ES6), 52 byte

n=>[...Array(n)].map((_,y,a)=>a.map(_=>y++%~-n<1|0))

7

V , 15 byte

Àé ÀÄ|r#L.|ò.kl

Provalo online!

Spiegazione

Àé<space>        " Argument times insert a space
ÀÄ               " Argument times duplicate this line
                 " This gives an arg-by-arg matrix of spaces
                 "  and brings the cursor to the end of the first line
|r#              " Go to the beginning of this line and replace the first character with #
L.               " Go to the end of this matrix (bottom-right corner) and replace that character with a #
|                " Go to the beginning of the last line
ò                " Recursively do:
 .               "  Repeat the last action, r#, replace the character under the cursor with #
 kl              "  Go 1 up and 1 right


5

GNU APL, 17 15 byte

{1=⍵∨⍵⍵⍴1=⍳⍵-1}

Questo è un giorno strano ... GNU in realtà ha battuto Dyalog APL ... woah.

TIO non supporta GNU APL ...

Spiegazione (input è ):

1=⍳⍵-1 - 1 followed by ⍵-2 0's
⍵⍵⍴    - fit into a square
⍵∨     - gcd ⍵ (0 gcd n = n)
1=     - test each element for equality with 1


Ecco ... prendilo.
Zacharý,

Non riesco a credere che in realtà ho dovuto rompere il mio vecchio APL GNU, wow.
Zacharý,

E prendilo !!
Zacharý,

Ooh, ho intenzione di prendere ispirazione da 1=⍵∨e implementarlo nella mia soluzione
Kritixi Lithos

5

Python 2 , 46 byte

lambda n:zip(*[iter(`10L**n`[:-3]*-~n+'1')]*n)

Provalo online!

Uscite come

[('1', '0', '0', '1'), ('0', '0', '1', '0'), ('0', '1', '0', '0'), ('1', '0', '0', '1')]

Python 2 , 48 byte

lambda n:zip(*[iter([1]+(n*[0]+[1])[2:]*-~n)]*n)

Provalo online!

Uscite come

[(1, 0, 0, 1), (0, 0, 1, 0), (0, 1, 0, 0), (1, 0, 0, 1)]

Python 3 , 48 byte

lambda n:('%d'*n+'\n')*n%(1,*(*[0]*n,1)[2:]*-~n)

Provalo online!

Un approccio alquanto diverso alla sostituzione delle stringhe in Python 3. Output come:

1001
0010
0100
1001

Non puoi fare 10L 10?
Zacharý,

@ Zacharý Sto facendo affidamento sul fatto che ci sia sempre un Lalla fine in modo da poter tagliare lo stesso numero di caratteri dalla fine di numeri grandi e piccoli.
xnor

Oh, scusa, ho erroneamente pensato che lo stessi usando solo come numero. Non l'ho mai saputo 10ed ero 10Ldiverso.
Zacharý,

4

Gelatina , 9 byte

=þ¹UF1Q¦s

Provalo online!

Come funziona

=þ¹UF1Q¦s  Main link. Argument: n

  ¹        Identity; yield n.
=þ         Equals table; compare each i in [1, ..., n] with each j in [1, ..., n].
           This yields the n×n identity matrix.
   U       Upend; reverse each row.
    F      Flatten the matrix.
       ¦   Sparse application:
      Q        Unique; yield the unique elements of the constructed array, i.e.,
               [1] if n = 1 and [0, 1] if n > 1.
     1         Yield 1.
           This replaces the elements at indices 0 (last) and 1 (first) with 1.
        s  Split the resulting array into chunks of length n.

4

APL (Dyalog) , 18 byte

{⍵=1:⍵⋄⍵ ⍵⍴1=⍳⍵-1}

Provalo online!

Far funzionare questo per l'input 1 ha aggiunto 6 byte.

Guardando la testcase 4, vediamo che l'output è

1 0 0 1
0 0 1 0
0 1 0 0
1 0 0 1

Questo è sostanzialmente 1 0 0 ripetuto in tutta la matrice. In altre parole, 1 0 0 ha modellato in una matrice 4 per 4. Quindi, in questa soluzione, prima generiamo questo vettore con 1 e trascinando 0 usando 1=⍳⍵-1e poi modellandolo usando ⍵ ⍵⍴. Ma questo si nasconde per l'ingresso 1, quindi dobbiamo creare un condizionale e guadagnare 6 byte ...

{⍵=1:⍵⋄⍵ ⍵⍴1=⍳⍵-1}    The right argument is 
 ⍵=1:⍵                 If  is 1 return itself
                      Otherwise
 ⍳⍵-1                   Create a range 1 .. ⍵-1
 1=                     Equals 1; 1 0 0 {⍵-2 0's} ...
 ⍵ ⍵⍴                   Shape in a ⍵-by-⍵ matrix

4

Haskell , 55 byte

Inizialmente il mio approccio era quello di generare ricorsivamente la matrice di identità trasposta, ma poi fissare la prima e l'ultima riga richiedeva alcune distinzioni tra brutti e lunghi casi. Quindi ho cercato un altro modo per generare la matrice identità che è come ho trovato questa idea.

f n=[[sum[1|x+y`elem`[2,n+1,2*n]]|y<-[1..n]]|x<-[1..n]]

Provalo online!

Spiegazione

[[x+y|y<-[1..n]]|x<-[1..n]]

genera questa matrice (per n=4):

[2,3,4,5]
[3,4,5,6]
[4,5,6,7]
[5,6,7,8]

Come puoi vedere, l'elemento in alto a sinistra è 2(in generale), tutti gli elementi diagonali sono 5(in generale n+1) e l'elemento in basso a destra è 8(in generale 2*n). Quindi tutto ciò che dobbiamo fare è verificare se x+yè un elemento di [2,n+1,2*n].


4

R , 54 42 byte

-12 byte grazie a Jarko Dubbeldam

n=scan();m=diag(n)[,n:1];m[1,1]=m[n,n]=1;m

restituisce una matrice; legge da stdin. crea una matrice identità diag(n), la capovolge dall'alto verso il basso [,n:1], imposta in alto a sinistra e in basso a destra 1, quindi scrive su console ( '') con larghezza n.

Provalo online!


È possibile generare una matrice, quindi è possibile salvare alcuni byte trasformandola in una funzione ( pryr::f).
JAD,

@JarkoDubbeldam Potrei, ma poi penso che dovrei cambiare la lingua in R+pryrmodo da considerare una lingua separata; sei libero di inviarlo! Quindi potresti usare l'idea della risposta del ciarlatano di Cows, che penso sarebbe ancora più breve di così in quel contesto (una riga).
Giuseppe,

Hmm, non sono sicuro di dove tracciare la linea per essere onesti. Considereresti che una biblioteca abbia usato una lingua diversa?
JAD

1
Inoltre, l'utilizzo function(n)sarebbe probabilmente ancora più breve
JAD

1
Che è più breve dell'implementazione oneliner a cui hai fatto riferimento:function(n)matrix(rep(c(1,rep(0,n-2)),n+1),n,n)
JAD

4

MATL , 7 byte

XyPl5L(

Provalo a MATL Online!

Spiegazione

Crea matrice identità ( Xy), capovolgi verticalmente ( P), scrivi ( () valore 1 ( l) alla prima e all'ultima voce ( 5L), che sono in alto a sinistra e in basso a destra.


4

Dyalog APL, 12 11 10 byte

,⍨⍴×,2↓⊢↑×

Provalo online

-1 byte grazie a lstefano.

Come?

,⍨⍴×,2↓⊢↑×
       ⊢↑× - argument-length extension of the sign of the argument (1)
     2↓    - Drop the first two elements
   ×,      - Prepend a one
,⍨⍴        - Shape into a square array with dimensions of input x input

Sinceramente non penso che questo possa più essere giocato a golf ... wow.
Zacharý,

Può: ,⍨⍴×,2↓⊢↑×(10 byte). Sono tentato di aggiungere: non usare troppi
spostamenti


Mi stai prendendo in giro, wow. Bello abuso di signum.
Zacharý,

3

C # (.NET Core) , 121 91 88 byte

-30 byte perché il vecchio modo era stupido.

-3 byte spostando l'inizializzazione della variabile

n=>{int i=0,k=n-1;int[,]b=new int[n,n];b[0,0]=b[k,k]=1;for(;i<n;)b[i++,k--]=1;return b;}

Provalo online!

I cicli scorre verso il basso l'array per riempire gli 1. Restituisce un array di 1 e 0.


Dichiarare bcome varsalvare alcuni byte.
TheLethalCoder

3

05AB1E , 14 11 7 byte

n<ÝI<Öô

Provalo online!

Spiegazione

n<Ý      # push range [0 ... n^2-1]
   I<Ö   # check each for equality to 0 when modulus with n-1 is taken
      ô  # split in pieces of size n

3

Carbone , 14 12 7 byte

-5 byte grazie a Neil !

↗N⸿/‖O↘

Provalo online!


Non credo che questo possa essere più breve ...
Erik the Outgolfer,

1
Bene, prima l'ho tagliato Nν◨/ν←↙ν‖O↘, ma poi mi è venuto in mente ↗N⸿/‖O↘!
Neil,

@Neil Wow, non so nemmeno cosa ⸿. Si ripristina alla posizione originale?
notjagan,

No, ⸿è come se si sposta verso il basso di una riga ma va sempre alla colonna zero (misurata da ) anziché alla colonna all'inizio della stringa, quindi ad esempio J⁵¦⁵⸿è la stessa J⁰¦⁶.
Neil,

3

C ++, 144 byte

#include<string>
#define S std::string
S p(int n){S r;for(int i=0;i<n;++i){r+=S(n,32);r[r.size()-1-i]=35;r+=10;}r[0]=r[r.size()-2]=35;return r;}

Sfrutta la differenza di un byte tra '#' e 35


Dove esattamente il tuo codice sfrutta la differenza di un byte tra '#'e 35?
Zacharý,

@ Zacharý Sembra che fosse nel mio IDE x)
HatsuPointerKun

2

Mathematica, 72 byte

(s=Table[0,#,#];s[[1,1]]=s[[#,#]]=1;Table[s[[#+1-i,i]]=1,{i,#}];Grid@s)&

ingresso

[5]

produzione

1 0 0 0 1
0 0 0 1 0
0 0 1 0 0
0 1 0 0 0
1 0 0 0 1


1
Il problema non richiede di stamparlo / visualizzarlo, quindi è possibile sostituirlo Grid@scon sper salvare 5 byte.
Mark S.


2

PowerShell , 67 byte

param($n)0..--$n|%{-join(("1"+"0"*(($n-1),0)[!$n])*3)[$_..($_+$n)]}

Provalo online!

Accetta input $ne loop da 0a --$n(cioè, $npre-decrementato). Ogni iterazione, costruiamo una stringa di 1seguita da $n-1 0s, quindi moltiplichiamo i 3tempi di uscita (ad esempio, 100010001000per l'input di 5). Quindi ci indicizziamo su base rotante a partire da 0a 0 + $n. Quei personaggi lo sono-join inseriti in una stringa, che viene lasciata sulla pipeline. L'output è implicito.


(NB: per gestire il caso speciale sono necessari altri 9 byte n=1. Di seguito è riportato il codice a 58 byte se siamo garantiti n>1)

param($n)0..--$n|%{-join(("1"+"0"*($n-1))*3)[$_..($_+$n)]}

2

Dyalog APL v16, 23 byte

{(1@(1 1)(⍵ ⍵))⌽∘.=⍨⍳⍵}

Provalo online!

Spiegazione:

{(1@(1 1)(⍵ ⍵))⌽∘.=⍨⍳⍵} -(input ⍵) 
                ∘.=⍨⍳⍵  - identity matrix with size ⍵×⍵
               ⌽        - flip that
 (1@(1 1)(⍵ ⍵))         - place 1 into the corners using the v16 operator @ (At)

2

Lua, 117 byte

m=arg[1]+0 for y=m,1,-1 do s=""for x=1,m do s=s..((x==1 and y==m or x==m and y==1 or x==y)and"#"or" ")end print(s)end

Provalo

Il codice è piuttosto semplice. Imposta m sul primo argomento, quindi aggiunge 0 ad esso per convertirlo in un numero, quindi scorre indietro per il coordio Y, in avanti attraverso il coordino X e inserirà un # se x == y o se sono gli altri angoli.

Questo programma non utilizza mai la parola chiave "if".


2

Ottava, 37 byte

@(n)sparse([1 n:-1:1 n],[1 1:n n],!0)

Provalo online!

Genera una matrice sparsa che rappresenta il segno di percentuale.


2

Japt , 12 byte

²ovUÉ hT1 òU

Restituisce una matrice / matrice 2D.

Provalo online! usando il-Q flag to show array-formatted output.

Spiegazione

²ovUÉ hT1 òU

Implicito: U= input intero

²o

Square U( ²), crea l'array [0, U*U)( o) e mappa ogni elemento per ...

vUÉ

1 if it's divisible (v) by U-1 (), else 0.

hT1

Set the item (h) at index 0 (T) to 1.

òU

Split the array into slices (ò) of length U.


I don't think you actually need the hT1, as 0 is technically already divisible by U for every U. Other than that, great job :-)
ETHproductions

@ETHproductions That was added to deal with an input of 1. Without it, it returns [[0]] because apparently zero is not divisible by zero.
Justin Mariner

Ah, dang it. I don't know if I should fix that though...
ETHproductions

2

PHP, 53 bytes

for(;$i<$l*$l;)echo($i++%($l-1)?0:1).($i%$l?'':"\n");

The length of the side of the matrix is $l. This code has a PHP Notice and even a PHP Warning for division by 0 when $l=0, but does the job!


It seems that you expect the input to be stored in a predefined variable (->$l). Unfortunately this is not one of our accepted ways to take input. In the linked meta post you'll find alternatives, e.g. using command line arguments as seen in ricdesi's answer.
nimi

completed and golfed: while($i**.5<$n=$argn)echo$i++%~-$n?0:1,"\n"[$i%$n]; or while($i**.5<$n=$argn)echo+!($i++%~-$n),"\n"[$i%$n]; (52 bytes each)
Titus

Needs <? at the beginning.
manassehkatz-Reinstate Monica


2

Ruby, 47 bytes

->n{([1]+[0]*(n-2)).cycle.each_slice(n).take n}

It returns an array of arrays.

The code is pretty straightforward.

  • It creates a n-1 array with 1 as the first element and the rest filled with 0s (e.g. [1, 0, 0, 0])
  • It repeats it
  • It takes n slices of n elements

Try it online!



2

Python 3, 97 bytes

def f(n):
    m=[[0+(j==n-i-1)for j in range(n)]for i in range(n)]
    m[0][0]=1
    m[-1]=m[0]
    return m

Explanation

m=[[0+(j==n-i-1)for j in range(n)]for i in range(n)]

This is a list comprehension, the 0+(j==n-i-1) is a shorter way to convert j==n-i-1 to an int (as opposed to int function) and then m[-1]=m[0] is shorter than making bottom right 1, as top and bottom rows are identical.


2

Forth, 273 ( without comments ) 170 ( golfed-ish )

: % 2 base ! cr dup 1- 1 swap lshift 1 or . cr 2 over 2 - dup 0< 0= if
0 ?do 2dup s>d rot <# 0 ?do # loop #> type cr 2*  loop
1 or . else drop drop then cr drop decimal ;

( 273 version to clarify commented version: )

: newbase
 base @ swap base ! ;
: 0u.r
 swap s>d rot <# 0 ?do # loop #> type ;
: frame
 1- 1 swap lshift 1 or ;
: %
 2 newbase swap
 cr dup frame . cr
 2 over 2 -
 dup 0< 0= if
  0 ?do
   2dup swap 0u.r cr
   2* 
  loop
  1 or .
 else
  drop drop
 then
cr
drop base ! ;

( Note that, since whitespace is the primary delimiter in Forth, removing every carriage return would make no difference. Indentation, of course, does. )

( Commented: )

( Uses bit array, max 64 width on AMD64 with gforth. )

( Could shave an extra thirty or so bytes by not restoring )
( the numeric base, )
( and a few more by pulling frame and 0u.r into the definition. )

: newbase ( n -- oldbase )  ( swap base with n )
 base @ swap base ! ;

: 0u.r ( u width -- )  ( unsigned numeric output, no leading zero suppression )
 swap s>d rot <# 0 ?do # loop #> type ;

: frame ( n -- f )  ( frame )
 1- 1 swap lshift 1 or ;

: %  ( n -- )  ( Make the % sign )
 2 newbase swap ( Use binary output. )
 cr dup frame . cr ( Frame the first line. )
 2 over 2 -
 dup 0< 0= if ( Are we already done? )
  0 ?do ( Loop doesn't do the first or last. )
   2dup swap 0u.r cr ( Zero fill, right justify. )
   2* 
  loop
  1 or . ( Put the second frame out. )
 else
  drop drop
 then
cr
drop base ! ;

( Execution examples: )

1 % 
1 

 ok
2 % 
11 
11 
 ok
3 % 
101 
010
101 
 ok
10 % 
1000000001 
0000000010
0000000100
0000001000
0000010000
0000100000
0001000000
0010000000
0100000000
1000000001 
 ok
40 % 
1000000000000000000000000000000000000001 
0000000000000000000000000000000000000010
0000000000000000000000000000000000000100
0000000000000000000000000000000000001000
0000000000000000000000000000000000010000
0000000000000000000000000000000000100000
0000000000000000000000000000000001000000
0000000000000000000000000000000010000000
0000000000000000000000000000000100000000
0000000000000000000000000000001000000000
0000000000000000000000000000010000000000
0000000000000000000000000000100000000000
0000000000000000000000000001000000000000
0000000000000000000000000010000000000000
0000000000000000000000000100000000000000
0000000000000000000000001000000000000000
0000000000000000000000010000000000000000
0000000000000000000000100000000000000000
0000000000000000000001000000000000000000
0000000000000000000010000000000000000000
0000000000000000000100000000000000000000
0000000000000000001000000000000000000000
0000000000000000010000000000000000000000
0000000000000000100000000000000000000000
0000000000000001000000000000000000000000
0000000000000010000000000000000000000000
0000000000000100000000000000000000000000
0000000000001000000000000000000000000000
0000000000010000000000000000000000000000
0000000000100000000000000000000000000000
0000000001000000000000000000000000000000
0000000010000000000000000000000000000000
0000000100000000000000000000000000000000
0000001000000000000000000000000000000000
0000010000000000000000000000000000000000
0000100000000000000000000000000000000000
0001000000000000000000000000000000000000
0010000000000000000000000000000000000000
0100000000000000000000000000000000000000
1000000000000000000000000000000000000001 
 ok

( Final note: works to one less than the bit width of the Forth interpreter. I ran the above on gforth, AMD64. An ancient 16-bit Forth would only go to 15 bits wide, and would need a bit of modification. )


If you want to have the commented code in your answer that's fine, but you do need the golfed down code somewhere, too.
Pavel

@Phoenix Thanks. Done.
Joel Rees

2

C# (.NET Core), 65 bytes

w=>{var l=new int[w*w];for(int i=0;i<w*w;i+=w-1)l[i]=1;return l;}

Try it online!

The algorithm is significantly distinct from the other C# answer, so I decided to post it separately rather than as an improvement. Inspired by the top rated Jelly answer actually, I was doing something slightly less compact before. The output is a linear array, so would require some logic to wrap it into a 2D outside the method as-is. An alternate version requires 6 additional bytes to output as a true 2D array:

w=>{var l=new int[w,w];for(int i=0;i<w*w;i+=w-1)l[i/w,i%w]=1;return l;}

I also have an interesting non-competing version.

using System.Linq;w=>new int[w*w].Select((_,i)=>i%(w-1)<1)

This ends up with almost the right output, resulting in an IEnumerable<bool> with true/false instead of 1/0, and it's a linear rather than 2D structure, and although not needed for that exact line of code, using System.Collections.Generic is necessary to do anything useful with the output. Like I said, it's very close to being valid but not quite.


For the second using a ternary as in ?1:0 works and I believe an array of the result should be fine. The collections using also isn't necessary for that code.
TheLethalCoder

For the first, would setting w*w to a variable and moving the int declaration out of the loop save you anything?
TheLethalCoder

@TheLethalCoder Replacing the two instances of w*w with a single character variable saves 4 bytes, moving int i=0 outside the loop requires a semicolon which costs 1 byte, and then adding ,s=w*w to the declaration costs 6 bytes, so it actually nets +3 bytes.
Kamil Drakari

You should use the byte count of the full 2D-representation solution. The array returned by the shorter solution would at least need to include some sort of delimiter to be valid.
Jakob
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.