Decodifica il chmod


26

Sfida

Dato un numero di autorizzazioni ottali a tre cifre, emettere le autorizzazioni che concede.

chmod

Sui sistemi operativi UNIX, le autorizzazioni dei file vengono modificate mediante il chmodcomando. Esistono diversi modi per utilizzare chmod, ma quello su cui ci concentreremo oggi è l'utilizzo dei permessi ottali.

Le tre cifre nel numero di autorizzazioni rappresentano una persona diversa:

  • La prima cifra rappresenta le autorizzazioni per l' utente
  • La seconda cifra rappresenta le autorizzazioni per il gruppo
  • L'ultima cifra rappresenta le autorizzazioni per gli altri

Successivamente, ogni cifra rappresenta un'autorizzazione come mostrato di seguito in:

Key: number | permission

7 | Read Write and Execute
6 | Read and Write
5 | Read and Execute
4 | Read only
3 | Write and Execute
2 | Write only
1 | Execute only
0 | None

Ingresso

L'input sarà il numero di tre cifre come una stringa, ad esempio:

133

o

007

Questo verrà passato tramite STDIN o tramite argomenti di funzione.

Produzione

Il tuo output dovrebbe essere le diverse autorizzazioni per ciascuno degli utenti, il gruppo e gli altri. È necessario visualizzare queste informazioni in questo modo:

User:   ddd
Group:  ddd
Others: ddd

Dove ci sono tre spazi dopo User, due spazi dopo Groupe uno spazio dopo Others. Si sostituisce dddcon le informazioni sulle autorizzazioni.

L'output potrebbe essere STDOUT o come stringa restituita.

Esempi

Ingresso: 666

Produzione:

User:   Read and Write
Group:  Read and Write
Others: Read and Write

Ingresso: 042

Produzione:

User:   None
Group:  Read only
Others: Write only

Ingresso: 644

Produzione:

User:   Read and Write
Group:  Read only
Others: Read only

vincente

Vince il codice più breve in byte.


Quali sono le specifiche dell'input?
Jonathan Allan,

@JonathanAllan Solo il numero di tre cifre
Decadimento beta

Intendi solo come numero intero decimale, quindi 042 verrebbe ricevuto come 42?
Jonathan Allan,

2
@Jonathan No, è un input di stringa, quindi sarebbe 042
Decadimento beta

1
L'output sembra corretto con un carattere di tabulazione, quindi perché non utilizzarlo? Solo per le lingue penali che hanno bisogno di più byte per riempire una stringa?
Tito

Risposte:


3

05AB1E , 89 87 byte

”‚Ý:‚Ù:ˆ†:”ð¡v”Šª0ÍÃ20‡í20‡í1ÍÃ0‚Ø20‚Ø1ÍÃ0‚Ø1‡í0‚؇í1ÍÔ2ð'€É«:1ð'€ƒ«:0ð«¡¹Nèèð3N-×ìyì,

Evoca la codifica Cthulhu . Utilizza la codifica CP-1252 . Provalo online!


14

Javascript (ES6), 165 161 byte

n=>[0,1,2].map(i=>(s='User:  3Group: 68Others:58None576Read48Write476Execute475and4576only'.split(/(\d+)/))[i*2]+s[n[i]*2+1].replace(/./g,c=>' '+s[c*2])).join`
`

Modifica: +1 byte per soddisfare la regola "nessuna scheda"

Esempi

let f =
n=>[0,1,2].map(i=>(s='User:  3Group: 68Others:58None576Read48Write476Execute475and4576only'.split(/(\d+)/))[i*2]+s[n[i]*2+1].replace(/./g,c=>' '+s[c*2])).join`
`
console.log(f("666"));
console.log(f("042"));
console.log(f("644"));
console.log(f("137"));


È possibile ottenere alcuni byte riorganizzando l'array (e forse separando i numeri dalle stringhe). +1 per l'idea.
Tito,

@Titus - Devo ammettere che non riesco a vedere un riarrangiamento che salva alcuni byte. Inoltre, i numeri devono essere trattati come stringhe in modo che funzionino replace()su di essi senza forzature. Ma potrei mancare il tuo punto.
Arnauld,

@Titus - Qualcosa del genere 'User3Group68Others58None576Read48Write476Execute475and4576only'.split(/(\d+)/)potrebbe funzionare. È quello che avevi in ​​mente?
Arnauld,

Li stavo fraintendendo; pensato che fossero valori ottali. :) Ma anche la tua nuova idea non è male.
Tito,

L'output della sfida richiede spazi anziché tabulazioni poiché è attualmente scritto.
Mwr247,

13

GNU sed, 187 163 158 (157 + 1) byte

Esegui con -r (ERE regexp). Il file non contiene newline finali.

s/(.)(.)/User:   \1\nGroup:  \2\nOthers: /g
s/[4-7]/Read &/g
s/[2367]/Write &/g
s/[1357]/Execute &/g
s/(\w) (\w+) [1-7]/\1 and \2/g
s/[1-7]/only/g
s/0/None/g

Approccio gradevole ma è possibile salvare circa 20 byte rimuovendo le cifre quando si aggiunge ando only.
Neil,

@Neil there :) ha incorporato il tuo suggerimento per un salvataggio molto significativo.
FireFly,

1
La prima riga potrebbe essere solo: s/(.)(.)/User: \1\nGroup: \2\nOthers: /. Alcuni byte in più potrebbero essere salvati eseguendo il port su Perl, che ha \de \K.
ninjalj,

@ninjalj buon punto. Continuerò a sed perché non conosco Perl, e sono sicuro che ci sarebbero altri trucchi da tirare lì per renderlo ancora più breve, al di fuori delle sostituzioni.
FireFly,

6

C # 214 byte

string h(string y){string e="Execute ",r="Read ",w="Write ",O="Only",a="and ";var z=new[]{"None",e+O,w+O,w+a+e,r+O,r+a+e,r+a+w,r+w+a+e};return$"User:   {z[y[0]-'0']}\nGroup:  {z[y[1]-'0']}\nOthers: {z[y[2]-'0']}";}

6

Gelatina , 100 91 85 byte

Quasi certamente golfable - 91 byte, che cosa ?! 8 mesi e 6 byte di saggezza!
- 1. maggiore compressione delle stringhe;
- 2. rimuovere il decremento post-ordinale di 48 poiché l'indicizzazione è modulare;
- 3. utilizzare un migliore concatenamento tacito).

-9 byte con il gentile aiuto di @Lynn che esegue compressioni di stringhe per me

,“£ɱ~»
Ñ
ṖK,“ and”,Ṫ
LĿK
7RBUT€Uị“ØJƓ“¥Ị£“¤/¡»Ç€“¡*g»ṭ
“ṖŒhJ"ỵd¡»ḲðJ4_⁶ẋ⁸,"j€”:ż⁹Oị¢¤Y

Provalo su TryItOnline

Come?

,“£ɱ~» - Link 1: pair with the string "Only"

Ñ - Link 2: call next link

ṖK,“ and”,Ṫ - Link 3: insert " and" between the last two elements of x
Ṗ           - x[:-1]
 K          - join with spaces
   “ and”   - the string " and"
          Ṫ - x[-1]
  ,      ,  - pair

LĿK - Link 4: call appropriate link and add missing spaces
L   - length
 Ŀ  - call link at that index
  K - join the result with spaces

7RBUT€Uị“ØJƓ“¥Ị£“¤/¡»Ç€“¡*g»ṭ - Link 5: construct all 8 cases
7R                            - range of 7: [1,2,3,4,5,6,7]
  B                           - binary (vectorises): [[1],[1,0],[1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]
   U                          - reverse (vectorises): [[1],[0,1],[1,1],[0,0,1],[1,0,1],[0,1,1],[1,1,1]]
    T€                        - indexes of truthy values for each: [[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
      U                       - reverse (vectorises): [[1],[2],[2,1],[3],[3, 1],[3,2],[3,2,1]]
        “ØJƓ“¥Ị£“¤/¡»         - list of strings: ["Execute","Write","Read"]
       ị                      - item at index (vectorises): [["Execute"],["Write"],["Write","Execute"],["Read"],["Read","Execute",["Read","Write"],["Read","Write","Execute"]]
                     ǀ       - call the previous link for each
                       “¡*g»  - the string "None"
                            ṭ - tack (Jelly is 1-based so the 8th item will be indexed as 0)

“ṖŒhJ"ỵd¡»ḲðJṚ⁶ẋ⁸,"j€”:ż⁹Oị¢¤Y - Main Link: parse input and make the result. e.g.: "042"
“ṖŒhJ"ỵd¡»                     - dictionary compression of "User Group Others"
          Ḳ                    - split at spaces -> ["User","Group","Others"]
           ð                   - dyadic chain separation, call that g (input as right)
            J                  - range of length of g -> [1,2,3]
             Ṛ                 - reverse -> [3,2,1]
              ⁶                - literal space
               ẋ               - repeat -> ["   ","  "," "]
                ⁸              - chain's left argument, g
                  "            - zip with:
                 ,             -   pair -> [["User","   "],["Group","  "],["Others"," "]]
                     ”:        - literal ':'
                   j€          - join for €ach -> ["User:   ","Group:  ","Others: "]
                            ¤  - nilad followed by link(s) as a nilad:
                        ⁹      - chain's right argument, the input string -> "042"
                         O     -   cast to ordinal (vectorises) -> [48, 52, 50]
                           ¢   -   call last link (5) as a nilad  -> ["Execute Only","Write Only","Write and Execute","Read Only","Read and Execute","Read and Write","Read Write and Execute","None"]
                          ị    -   index into (1-based & modular) -> ["None","Read Only","Write Only"]
                       ż       - zip together -> [["User:   ","None"],["Group:  ","Read Only"],["Others: ","Write Only"]]
                             Y - join with line feeds -> ["User:   ","None",'\n',"Group:  ","Read Only",'\n',"Others: ","Write Only"]
                               - implicit print:
                                             >>>User:   None
                                             >>>Group:  Read Only
                                             >>>Others: Write Only

4

Ottava, 185 byte

@(n)fprintf('User:   %s\nGroup:  %s\nOthers: %s',{'Read Write and Execute','Read and Write','Read and Execute','Read only','Write and Execute','Write only','Execute only','None'}{56-n})

Crea una funzione anonima che accetta l'input come stringa: '042'. Convertirlo in un array: (56-'042)' = [0 4 2]. Usalo come più indici di cella con cui indicizzare l'array di celle Read Write and Execute','Read and Write', .... Usi fprintfper emettere i tre archi, con le categorie appropriate: User:, Group:e Others:.

Ho provato a trovare un modo per negozio Execute, Write, Readcome parole separate e concatenare come necessario, ma questo si è rivelato più lungo del approccio ingenuo.

Esempi:

1> f('000')
User:   None
Group:  None
Others: None
2> f('042')
User:   None
Group:  Read only
Others: Write only

Provalo online.


2
È possibile salvare alcuni byte usando al strsplit('Read Write and Execute*Read and Write*Read and Execute*Read only*Write and Execute*Write only*Execute only*None','*')posto del letterale array di celle
Luis Mendo,

4

PowerShell v2 +, 189 168 byte

[char[]]$args[0]|%{('User','Group','Others')[$i++]+":`t"+('None','Read','Write','Execute','only','and')[(0,(3,4),(2,4),(2,5,3),(1,4),(1,5,3),(1,5,2),(1,2,5,3))[$_-48]]}

Passa attraverso l'input $args[0]come una charmatrice. Ogni iterazione, indicizziamo in un array con $i++(il valore predefinito è 0) per selezionare User, Groupo Others, concatenarlo con due punti e una scheda e concatenarlo con un altro indice di array.

Ecco la magia. Abbiamo implicitamente castato charin an inte sottratto 48(cioè trasformando ASCII 48( "0") in 0), scegliendo la formulazione appropriata come una matrice di ints. Tale array viene successivamente utilizzato come indice 'None','Read','Write','Execute','only','and'nell'array. Poiché il valore predefinito $ofs(Output Field Separator) è uno spazio, questo inserisce correttamente gli spazi tra gli elementi dell'array quando sono sottoposti a stringhe (cosa che accade quando si concatena a sinistra).

Queste tre stringhe vengono lasciate sulla pipeline e l'output tramite implicito Write-Outputavviene al completamento del programma.

Esempio

PS C:\Tools\Scripts\golfing> .\decode-the-chmod.ps1 '123'
User:   Execute only
Group:  Write only
Others: Write and Execute

3

Paglia , 193 byte

((01234567)((None)(Execute only)(Write only)(Write and Execute)(Read only)(Read and Execute)(Read and Write)(Read Write and Execute)))::~<:{-¢(User:   ),+>
>}:{-¢(Group:  ),+>
>}-¢(Others: ),+>

Provalo online

Premi 3 volte una tabella di conversione sul primo stack, passa al secondo stack, converti ciascun numero utilizzando la tabella di conversazione e stampa.


2

Haskell, 186 byte

s=zip(words"7654 6 7632 753 7531 0 421")(words"Read and Write and Execute None only")
m c=mapM_(\(x,y)->putStrLn(x++unwords[b|(a,b)<-s,elem y a]))$zip["User:   ","Group:  ","Others: "]c

Esempio:

Prelude> :r
[1 of 1] Compiling Main             ( decCh.hs, interpreted )
Ok, modules loaded: Main.
*Main> m "654"
User:   Read and Write
Group:  Read and Execute
Others: Read only

Usato solo Preludio. Lo sto facendo bene?

Ungolfed:

s = zip (words "7654 6 7632 753 7531 0 421")
        (words "Read and Write and Execute None only")

ps y = unwords [b|(a,b)<-s,elem y a] -- build permissions string
pp (x,y) = putStrLn $ x ++ ps y -- print user + permission

m c =   let up = zip ["User:   ","Group:  ","Others: "] c -- pair user and permission
        in mapM_ pp up --print each

2

Python 2, 190 185 byte

def f(i):
 r,w,a,x,o,g="Read ","Write ","and ","Execute ","only",["User:  ","Group: ","Others:"];p=["None",x+o,w+o,w+a+x,r+o,r+a+x,r+a+w,r+w+a+x]
 for z in 0,1,2:print g[z],p[int(i[z])]

Lascia uno spazio finale se Esegui o Scrivi sono alla fine della riga ma non ho visto che ciò non era consentito.

EDIT Salvato 5 byte modificando l'intervallo (3) su 0,1,2 e controllando il conteggio dei byte sul mio laptop Linux anziché su quello di Windows (\ n = \ r \ n o viceversa. Non ricordo mai quale).


2

Python 2, 240 239 238 237 228 byte

Ho pensato di provare finalmente questa fredda cosa da golf. Si spera che sia consentito il trascinamento di spazi bianchi. (risolto e nel processo salvato un byte)

i=0
def a(b):
 for d in 4,2,1:
    if b&d:yield('Execute','Write','Read')[d/2]
for k in raw_input():
 b,q=list(a(int(k))),' and';e=len(b)
 if e:b[~e/2]+=(' only',q,q)[e-1]
 print'UGOsrteohrue:pr :s  :'[i::3],' '.join(b)or None;i+=1

Benvenuto in PPCG e bella prima risposta!
ETHproductions

Ho spudoratamente sostituito l'intervallo (3) nella mia risposta Python 2 a 0,1,2 dopo aver letto il tuo codice. Bella risposta. +1
ElPedro,

2

PHP, 169 159 byte

foreach([User,Group,Others]as$i=>$u){echo"
$u: ";for($n=[5,33,34,66,35,67,131,531][$i]];$n;$n>>=3)echo["and",Execute,Write,Read,only,None][$n&7]," ";}

prende stringa come argomento della riga comandi: php -r '<code>' <argument>,
stampa una nuova riga leader invece di uno trascinamento

Grazie a Jörg per aver segnalato i miei bug e per il \t .

PHP, 169 byte

con la nuova restrizione: (carattere tab vietato)

foreach(['User:  ','Group: ','Others:']as$i=>$u){echo"
$u";for($n=[5,33,34,66,35,67,131,531][$argv[1][$i]];$n;$n>>=3)echo' ',['and',Read,Write,Execute,only,None][$n&7];}

Questo è più corto di 1 byte rispetto a str_pad, a causa dello spazio aggiuntivo necessario.

abbattersi

foreach([User,Group,Others]as$i=>$u)
{
    echo"\n$u:\t";                      // print newline, who, blanks
    for($n=[5,33,34,66,35,67,131,531]   // octal values for words indexes
        [$argv[1][$i]]                  // (last word=highest digit)
        ;$n;$n>>=3)                     // while value has bits left
        echo['and',Execute,Write,Read,only,None][$n&7]," "; // print that word
}

Per creare l'array per $n, usare questo:

$b=[[5],[1,4],[2,4],[2,0,1],[3,4],[3,0,1],[3,0,2],[3,2,0,1]];
foreach($b as$i=>$a){for($v=$j=0;$a;$j+=3)$v+=array_shift($a)<<$j;echo"$v,";}

1
foreach ([ 'utente', 'gruppo', 'Altro'] come $ i => $ u) {echo "\\ n $ u: \\ t"; salva alcuni byte e l'output per 3,4,6 è errato
Jörg Hülsermann

1
Questo è l'ordine giusto [5,33,34,66,35,67,131,531] bella idea
Jörg Hülsermann

Ho dimenticato "Utente" per l'utente per esempio salva i successivi 6 byte che vuoi battere JavaScript fallo
Jörg Hülsermann

@ JörgHülsermann: stavo per adottare la "\ t" comunque; Grazie. +1 per quello :) Buon occhio al 33!
Titus

1
per 346 il nostro output è Utente: gruppo di lettura e scrittura: esegui solo altri: scrivi ed esegui come dovrebbe Utente: scrivi ed esegui gruppo: sola lettura Altri: leggi e scrivi
Jörg Hülsermann

2

bash - 221 213 byte

GNU bash, version 4.3.46

l=("User:   " "Group:  " "Others: ")
o=\ only;a=" and ";x=Execute;w=Write;r=Read
b=(None "$x$o" "$w$o" "$w$a$x" "$r$o" "$r$a$x" "$r$a$w" "$r $w$a$x")
for c in `echo $1|grep -o .`;{ echo "${l[$((z++))]}${b[$c]}";}

Non è chiaro se questo può essere ulteriormente condensato, almeno non senza cambiare sostanzialmente l'approccio qui (suddividendo l'input e utilizzandolo come indice per l'array ${b}che contiene le stringhe corrispondenti).


1
È più corto con \ onlyinline espanso. grep -o .<<<$1è più breve di echo $1|grep -o ., ma while read -n1 cè meglio leggere l'input da stdin con . Gli indici di matrice hanno un contesto aritmetico in bash, quindi ${l[z++]}funziona. lsarebbe più breve come una stringa, a cui si accederà come ${l:z++*8:8}(offset e lunghezza hanno un contesto aritmetico). Un altro byte può essere salvato leggendo l'intera modalità c, espandendo "Utente:", ... in linea e facendo un uso giudizioso delle espansioni dei parametri.
ninjalj,

1
Per un risultato finale di: a=" and ";x=Execute;w=Write;r=Read;b=(None $x\ only $w\ only "$w$a$x" $r\ only "$r$a$x" "$r$a$w" "$r $w$a$x");read c;echo "User: ${b[${c%??}]}\nGroup: ${b[${c:1:1}]}\nOthers: ${b[${c:2}]}"(sostituisci \ n con newline letterali).
ninjalj,

1

Java 7, 300 284 byte

String c(String s){char[]a=s.toCharArray();return"User:   "+f(a[0])+"Group:  "+f(a[1])+"Others: "+f(a[2]);}String f(int i){return new String[]{"None","Execute only","Write only","Write and Execute","Read only","Read and Execute","Read and Write","Read Write and Execute"}[i%48]+"\n";}

Approccio diretto per ora. Proverà a trovare un approccio più generico per riutilizzare le parole.

Casi non testati e test:

Provalo qui.

class M{
  static String c(String s){
    char[] a = s.toCharArray();
    return "User:   " + f(a[0]) + "Group:  " + f(a[1]) + "Others: " + f(a[2]);
  }

  static String f(int i){
    return new String[]{ "None", "Execute only", "Write only", "Write and Execute", "Read only", "Read and Execute", "Read and Write", "Read Write and Execute" }
      [i % 48] + "\n";
  }

  public static void main(String[] a){
    System.out.println(c("666"));
    System.out.println(c("042"));
    System.out.println(c("644"));
  }
}

Produzione:

User:   Read and Write
Group:  Read and Write
Others: Read and Write

User:   None
Group:  Read only
Others: Write only

User:   Read and Write
Group:  Read only
Others: Read only

1

Groovy, 217 207 205 byte

def c(m){def i=0,e='Execute',w='Write',r='Read',o=' only',a=' and ';m.each{println(['User:   ','Group:  ','Others: '][i++]+['None',"$e$o","$w$o","$w$a$e","$r$o","$r$a$e","$r$a$w","$r $w$a$e"][it as int])}}

ungolfed:

def c(m) {
  def i=0,e='Execute',w='Write',r='Read',o=' only',a=' and ';
  m.each{
    println(['User:   ','Group:  ','Others: '][i++]+['None',"$e$o","$w$o","$w$a$e","$r$o","$r$a$e","$r$a$w","$r $w$a$e"][it as int])
  }
}

1

Mathematica, 211 byte

{r,w,e,o,a}={"Read ","Write ","Execute ","only ","and "};""<>Transpose@{{"User:   ","Group:  ","Others: "},"None"[{e,o},{w,o},{w,a,e},{r,o},{r,a,e},{r,a,w},{r,w,a,e}][[#]]&/@IntegerDigits[#,10,3],"\n"&~Array~3}&

Un'implementazione semplice (probabilmente facilmente battibile): non calcola nulla, solo codifica ogni possibile output. L'input è un numero intero; genera ogni riga con uno spazio finale e una nuova riga finale complessiva.

IntegerDigits[#,10,3]fornisce le tre cifre dell'input (anche se ci sono zeri iniziali). Ogni cifra indica un argomento della "funzione"

"None"[{e,o},{w,o},{w,a,e},{r,o},{r,a,e},{r,a,w},{r,w,a,e}]

con 0 che indica il nome della funzione stessa. ""<>concatena tutte le stringhe in un elenco (di elenchi). "\n"&~Array~3produce le tre nuove linee.


Ho appena notato che la mia risposta in Python 2 è quasi identica alla tua, anche usando gli stessi nomi di variabili. Onestamente non avevo visto il tuo prima di pubblicare!
ElPedro,

1
nessun problema! Penso che la corrispondenza dei nomi delle variabili sia quasi prevedibile in questa situazione :)
Greg Martin,

Immagino che tu abbia ragione. I nomi delle variabili erano un po 'prevedibili ☺
ElPedro

tra +1, pensiamo allo stesso modo :-)
ElPedro

1
a proposito, non conosco Mathematica ma penso che potresti essere in grado di perdere un byte rimuovendo lo spazio da "solo". Sarà sempre alla fine di una linea, quindi non ha bisogno di uno spazio finale.
ElPedro,

1

Java 7, 278

golfed:

String f(String i){String o="";for(int n=0;n<i.length();)o+=(n<1?"User:   ":n<2?"Group:  ":"Others: ")+new String[]{"None","Execute only","Write only","Write and Execute","Read only","Read and Execute","Read and Write","Read Write and Execute"}[i.charAt(n++)-48]+"\n";return o;}

Ungolfed:

  String f(String i) {
    String o = "";
    for (int n = 0; n < i.length();)
      o += (n < 1 ? "User:   " : n < 2 ? "Group:  " : "Others: ")
        + new String[] { "None", "Execute only", "Write only", "Write and Execute", "Read only", "Read and Execute",
            "Read and Write", "Read Write and Execute" }[i.charAt(n++) - 48]
        + "\n";
    return o;
  }

Produzione:

User:   Read and Write
Group:  Read and Write
Others: Read and Write

User:   None
Group:  Read only
Others: Write only

User:   Read and Write
Group:  Read only
Others: Read only

1

Python 3.5, 3,6 - 235 232 228 216 byte

(dovrebbe funzionare su tutti i Python 3.x)

Quindi l'ingresso è su STDIN qui (salva un'importazione ☺).

a=input()
r=range
for i in r(3):
 p=int(a[i]);x=[["Read","Write","Execute"][j]for j in r(3)if 4>>j&p]
 if x[1:]:x[-1:-1]="and",
 if len(x)==1:x+="only",
 print(["User:  ","Group: ","Others:"][i]," ".join(x)or"None")

Facendo uso di tuple, omettendo gli spazi ove possibile e la precedenza dell'operatore in cui normalmente si inseriscono le parentesi per chiarire le proprie intenzioni.

Esempio di utilizzo:

$ echo -n '666' | python3 golf2.py
User:   Read and Write
Group:  Read and Write
Others: Read and Write
$ echo -n '644' | python3 golf2.py
User:   Read and Write
Group:  Read only
Others: Read only
$ echo '042' | python3 golf2.py
User:   None
Group:  Read only
Others: Write only
$ echo '123' | python3 golf2.py
User:   Execute only
Group:  Write only
Others: Write and Execute
$ echo -n '777' | python3 golf2.py
User:   Read Write and Execute
Group:  Read Write and Execute
Others: Read Write and Execute

Un-giocato a golf:

input_perms = list(map(int, input()))

entities = ["User", "Group", "Others"]
perm_names = ["Read", "Write", "Execute"]

for i in range(3):
    bits = input_perms[i]
    perms = [
        perm_names[j]
        for j in range(3)
        if (1 << (2-j)) & bits
    ]

    if len(perms) > 1:
        perms.insert(-1, "and")
    if len(perms) == 1:
        perms.append("only")

    print("{:7} {}".format(
        entities[i]+":",
        " ".join(perms) or "None"
    ))

1

Lotto, 280 byte

@echo off
set/pc=
call:l "User:   " %c:~0,1%
call:l "Group:  " %c:~1,1%
call:l "Others: " %c:~2,1%
exit/b
:l
for %%s in (None.0 Execute.1 Write.2 "Write and Execute.3" Read.4 "Read and Execute.5" "Read and Write.6" "Read Write and Execute.7") do if %%~xs==.%2 echo %~1%%~ns

La codifica hardware delle stringhe è stata di 47 byte più corta rispetto al tentativo di metterle insieme. Sarebbe stato 267 byte se le schede fossero legali.


1

C # 307 241 210 byte

string X(string s){var z="User: ,Group: ,Others:,5,34,14,123,04,023,021,0123,Read,Write,and,Execute,only,None".Split(',');return string.Join("\n",s.Zip(z,(a,b)=>b+z[a-45].Aggregate("",(x,y)=>x+" "+z[y-37])));}

formattato

string X(string s)
{
    var z = "User:  ,Group: ,Others:,5,34,14,123,04,023,021,0123,Read,Write,and,Execute,only,None".Split(',');
    return string.Join("\n", s.Zip(z, (a, b) => b + z[a - 45].Aggregate("", (x, y) => x + " " + z[y - 37])));
}

1

C #, 322 337 348 byte

Questa non è sicuramente la versione più breve, ma ho provato a risolvere questo problema usando operatori bit a bit poiché i chmodvalori sono in realtà flag di bit. Anche C # probabilmente non è il miglior linguaggio per giocare a golf: D

string P(string s){Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");return a.Count>1?string.Join(" ",a.Take(a.Count-1))+" and "+a.Last():a.Count>0?a.First()+" only":"none";};return string.Join("\n",(new[]{"User:   ","Group:  ","Others: "}).Select((c,i)=>c+X(s[i]-'0')));}

ungolfed: (con commenti)

string P(string s)
{
    // Function that determines the permissions represented by a single digit (e.g. 4 => "Read only")
    Func<int, string> X = p => 
    {
        var a = new List<string>();         // temporary storage for set permissions
        if ((p & 4) > 0) a.Add("Read");     // Read bit set
        if ((p & 2) > 0) a.Add("Write");    // Write bit set
        if ((p & 1) > 0) a.Add("Execute");  // Execute bit set

        // actually just Output formatting ... Takes a lot of bytes *grr*
        return a.Count > 1 
            ? string.Join(" ", a.Take(a.Count - 1)) + " and " + a.Last() 
            : a.Count > 0 
                ? a.First() + " only" 
                : "none";
    };

    // Actual result:
    return string.Join("\n", (new[] { "User:   ", "Group:  ", "Others: " })
        .Select((c, i) => c + X(s[i] - '0'))); // Map "User, .." to its permissions by using above function
}

Questa è la prima volta che gioco a golf, quindi per favore dimmi, se ho fatto qualcosa di sbagliato :)

MODIFICA 1:

Ho salvato alcuni byte sostituendoli s[i]-'0'con s[i]&7(alla fine) e salvando il conteggio delle liste in variabili:

string P(string s){Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");var c=a.Count;return c>1?string.Join(" ",a.Take(c-1))+" and "+a.Last():c>0?a[0]+" only":"none";};return string.Join("\n",(new[]{"User:   ","Group:  ","Others: "}).Select((c,i)=>c+X(s[i]&7)));}

MODIFICA 2:

Modificato in espressione lambda:

s=>{Func<int,string>X=p=>{var a=new List<string>();if((p&4)>0)a.Add("Read");if((p&2)>0)a.Add("Write");if((p&1)>0)a.Add("Execute");var c=a.Count;return c>1?string.Join(" ",a.Take(c-1))+" and "+a.Last():c>0?a[0]+" only":"none";};return string.Join("\n",(new[]{"User:   ","Group:  ","Others: "}).Select((c,i)=>c+X(s[i]&7)));}

1

Javascript, 213 209 208 188 186 byte

function(d){a=" and ";r="Read";w="Write";e="Execute";v=";";o=" only";c=["None",e+o,w+o,w+a+e,r+o,r+a+e,r+a+w,r+" "+w+a+e];return"User: "+c[d[0]]+"\nGroup: "+c[d[1]]+"\nOthers: "+c[d[2]]}

Risparmiato 20 byte grazie a Dada!


3
Potrei sbagliarmi, ma il tuo array non dovrebbe essere nell'ordine opposto? Se chiamo b ("000"), restituisce "Leggi Scrivi ed Esegui" mentre ci si potrebbe aspettare "Nessuno" ...
Dada,

E sono abbastanza sicuro che questo potrebbe essere più golfato. Per esempio, una versione di 191 byte di: function b(p){a=" and ";r="Read";w="Write";e="Execute";v=";";o=" only";c=["None",e+o,w+o,w+a+e,r+o,r+a+e,r+a+w,r+" "+w+a+e];return"User: "+c[p[0]]+"\nGroup: "+c[p[1]]+"\nOthers: "+c[p[2]]}.
Dada,

1

Visual Basic, 606 byte

imports System.Collections
module h
sub main()
Dim i As String=console.readline()
Dim s=new Stack(new String(){"Others: ","Group:  ","User:   "})
for each j as Char in i
dim t=new Stack()
if((asc(j) MOD 2)=1)then t.push("Execute")
if(asc(j)=50 or asc(j)=51 or asc(j)=54 or asc(j)=55)then t.push("Write")
if(asc(J)>51)then t.push("Read")
if t.count=3 then
w(s.pop+t.pop+" "+t.pop+" and "+t.pop)
else
if t.count=2 then
w(s.pop+t.pop+" and "+t.pop)
else
if t.count=0 then
w(s.pop+"None")
else
w(s.pop+t.pop+" only")
end if
end if
end if
next
end sub
sub w(s As String)
console.writeline(s)
end sub
end module

1
Benvenuti in PPCG! Bella prima risposta BTW :)
Decadimento beta

1

Crystal, 200 194 byte

def m(y)y=y.chars.map &.to_i
a=" and "
o=" only"
r="Read"
w="Write"
x="Execute"
c=["None",x+o,w+o,w+a+x,r+o,r+a+x,r+a+w,r+" "+w+a+x]
"User:   "+c[y[0]]+"
Group:  "+c[y[1]]+"
Others: "+c[y[2]]end

restituisce la stringa risultante per una determinata sequenza ottale come stringa. ad esempio: m("670")i risultati a: User: Read and Write\nGroup: Read Write and Execute\nOthers: None.

Provalo online .


0

C #, 371 byte

public String[] a = {"none","Execute only","Write only","Write and Execute","Read only","Read and Execute","Read and Write","Read Write and Execute"};
public String pA(int i){return a[i];}
public int d(int n,int i){
  n=n/Math.pow(10,i);
  return n%=10;
}
public void main(int i){
  Console.Write("User:\t{0}\nGroup:\t{1},Others:\t{2}",pA(d(i,0)),pA(d(i,1)),pA(d(i,2));
}

4
Questo è code-golf, quindi devi golf il tuo codice. Inoltre, aggiungi un'intestazione con il nome della lingua e il bytecount.
TuxCrafting,

Ho aggiunto il tuo numero di byte, che è il tuo punteggio. Devi vincere il punteggio più basso possibile per vincere
Decadimento Beta

Ad esempio, ti sbarazzi di tutto lo spazio bianco non necessario in ogni funzione
Decadimento beta

1
@BetaDecay Grazie, sono nuovo di questa community e penso che sarebbe meglio usare php invece che potrebbe portare a più codici compatti.
Alireza Tabatabaeian,

1
@Alireza Questa è una buona idea. Anche se su questo sito, ci piace vedere brevi risposte in Java e C # :)
Decadimento beta

0

Python 3.5 - 370 294 243 byte

golfed:

import sys
a=lambda o: [print(('User:  ','Group: ','Others:')[n],('None','Execute only','Write only','Write and Execute','Read only','Read and Execute','Read and Write','Read Write and Execute')[int(o[n])]) for n in range(0,3)]
a(sys.argv[1])

Controllo dimensioni:

$ du -b OctalToHuman.py 
243     OctalToHuman.py

Un-giocato a golf:

#!/usr/bin/env python3
from sys import argv as ARGS

types = ('User:  ', 'Group: ', 'Others:')
perms = ('None','Execute only','Write only','Write and Execute','Read only','Read and Execute','Read and Write','Read Write and Execute')

def convert(octal_string):
    for n in range(0,3):
        print(types[n], perms[int(octal_string[n])])

if __name__ == '__main__':
    convert(ARGS[1])

Uscita campione:

$ python ./OctalToHuman.py 666
User:   Read and Write
Group:  Read and Write
Others: Read and Write

$ python ./OctalToHuman.py 042
User:   None
Group:  Read only
Others: Write only

$ python ./OctalToHuman.py 644
User:   Read and Write
Group:  Read only
Others: Read only

Questo non è un serio contendente per i criteri vincenti. Richiediamo a tutte le risposte di fare un serio tentativo di ottimizzare il loro punteggio in base ai criteri vincenti (ad esempio, nelle sfide di code golf come questa, gli invii devono fare un serio tentativo di ridurre al minimo il numero di byte del programma).
Mego,

Puoi salvare parecchi byte rimuovendo import syse rendendo il programma una funzione anonima ( lambda o:...).
NoOneIsHere

0

F #, 204 203 byte

il mio primo golf, quindi ti prego di perdonare eventuali errori;)
La versione golf (basata 1: 1 sulla risposta di pinkfloydx33 ):

fun(y:string)->let e,r,w,o,a="Execute ","Read ","Write ","only","and ";let z=["None";e+o;w+o;w+a+e;r+o;r+a+e;r+a+w;r+w+a+e;];let(!-)a=z.[int y.[a]-48];sprintf"User:   %s\nGroup:  %s\nOthers: %s"!-0!-1!-2

La versione ungolfed:

fun (y : string) ->
    let e, r, w, o, a = "Execute ", "Read ", "Write ", "only", "and "
    let z = [
                "None";
                e + o;
                w + o;
                w + a + e;
                r + o;
                r + a + e;
                r + a + w;
                r + w + a + e;
            ]
    let (!-) a = z.[int(y.[a]) - 48]
    sprintf "User:   %s\nGroup:  %s\nOthers: %s" !-0 !-1 !-2

Esempio di utilizzo:

let k =  ...... // function definition goes here

printf"%s"<|k"755"
printf"%s"<|k"042"
// etc ...


Questo serve solo a verificare se potrei "migliorare" la risposta di pinkfloydx33 : non mi prendo alcun credito per l'algoritmo


0

PHP, 199 byte

foreach([User,Group,Others]as$i=>$u){$a=[];foreach([Read,Write,Execute]as$k=>$s)if($argv[1][$i]&4>>$k)$a[]=$s;$a[]=($x=array_pop($a))?$a?"and $x":"$x only":None;echo str_pad("\n$u:",9).join(" ",$a);}

PHP, 189 byte con \ t

foreach([User,Group,Others]as$i=>$u){$a=[];foreach([Read,Write,Execute]as$k=>$s)if($argv[1][$i]&4>>$k)$a[]=$s;$a[]=($x=array_pop($a))?$a?"and $x":"$x only":None;echo"\n$u:\t".join(" ",$a);}

Ehi, dovresti usare gli spazi invece delle schede
Decadimento beta

In questo caso \ t sembra str_repeat ("", 3- $ i) o str_pad ("", 3- $ i, "") ma non ha importanza per la mia idea, non ho alcuna possibilità di vincere. Se dovessi prendere un altro spazio cs.tut.fi/~jkorpela/chars/spaces.html
Jörg Hülsermann

1
13 + 34 byte da salvare. Nella versione lunga: utilizzare echo str_pad("$u:",8)invece di echo"$u:".str_repeat(" ",3-$i)(-9); questo rende $i=>obsoleto (-4). In entrambe le versioni: utilizzare $a[$z-1]="and $a[$z-1]";invece di {$a[]=$a[$z-1];$a[$z-1]="and";}(-7) e else$a[]=$a?Only:None;anziché elseif($z<1)$a[]=None;else$a[]=Only;(-14). Trasforma if(1<$z=count($a))$a[$z-1]="and $a[$z-1]";else$a[]=$a?Only:None;in if($x=array_pop($a))$a[]=$a?"and $x":"$x Only";else$a[]=None;(-3) e poi in $a[]=($x=array_pop($a))?$a?"and $x":"$x Only":None;(-10)
Tito

@Titus echo str_pad ("$ u:", 8), $ a [$ z-1] = "e $ a [$ z-1]" ;, altrimenti $ a [] = $ a? Solo: nessuno; Fatto $ i => obsoleto, non posso farlo, quindi è necessario $ m = $ argv [1] [$ i]. Per il resto, proverei prima in un altro modo. Grazie per l'input
Jörg Hülsermann,

1
Altre idee: if(4&$m=$argv[1][$i])invece di $m=$argv[1][$i];if(4&$m)(-3) O sostituisci $m=;if();if();if();con un cappio: foreach([Read,Write,Execute]as$k=>$s)if($argv[1][$i]&4>>$k)$a[]=$s;(-7)
Tito

0

Python 3, 191 byte

def d(n):a,b,c,d,e=' and ',' only',"Execute","Write","Read";l=["None",c+b,d+b,d+a+c,e+b,e+a+c,e+a+d,e+" "+d+a+c];y,u,i=map(int,n);return"User:   %s\nGroup:  %s\nOthers: %s\n"%(l[y],l[u],l[i])

ungolfed

def d(n):
    a,b,c,d,e=' and ',' only',"Execute","Write","Read"
    l=["None",c+b,d+b,d+a+c,e+b,e+a+c,e+a+d,e+" "+d+a+c]
    y,u,i=map(int,n)
    return"User:   %s\nGroup:  %s\nOthers: %s\n"%(l[y],l[u],l[i])

1
Benvenuti in PPCG! bel primo post!
R

Sono molto curioso di sapere come il moderatore ha 151 byte quando ottengo solo 191: D È un errore? Controlla le modifiche
Aleksandr Smirnov,

Sono stato io, scusa. Ho digitato nella modifica. Riparato ora.
R

0

Javascript (ES6), 159 byte

a=>`User:  ${(b=[' None',(c=' Execute')+(d=' only'),(e=' Write')+d,f=e+(g=' and')+c,(h=' Read')+d,h+g+c,h+g+e,h+f])[a[0]]}\nGroup: ${b[a[1]]}\nOthers:`+b[a[2]]

Esempio:

(a=>`User:  ${(b=[' None',(c=' Execute')+(d=' only'),(e=' Write')+d,f=e+(g=' and')+c,(h=' Read')+d,h+g+c,h+g+e,h+f])[a[0]]}\nGroup: ${b[a[1]]}\nOthers:`+b[a[2]])("042")
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.