解码chmod


26

挑战

给定一个三位数的八进制权限号,输出它授予的权限。

chmod

在UNIX OS上,使用以下chmod命令可以更改文件许可权。使用chmod的方法很少,但是我们今天将重点讨论的是使用八进制权限。

权限编号中的三个数字代表一个不同的人:

  • 第一位代表用户的权限
  • 第二位数字表示该的权限
  • 最后一位代表他人的权限

接下来,每个数字代表一个权限,如下所示:

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

输入项

输入将是字符串的三位数,例如:

133

要么

007

这将通过STDIN或通过函数参数传递。

输出量

您的输出应该是用户,组和其他用户的不同权限。您必须这样显示此信息:

User:   ddd
Group:  ddd
Others: ddd

后面有三个空格,后面有User两个空格,后面有Group一个空格Others。您将替换ddd为权限信息。

您的输出可能是STDOUT或返回的字符串。

例子

输入: 666

输出:

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

输入: 042

输出:

User:   None
Group:  Read only
Others: Write only

输入: 644

输出:

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

获奖

以字节为单位的最短代码获胜。


输入的规格是什么?
乔纳森·艾伦

@JonathanAllan只是三位数
β衰变

您的意思是仅作为十进制整数,所以042将被接收为42?
乔纳森·艾伦

2
@Jonathan不,这是一个字符串输入,所以应该是042
Beta Decay

1
输出看起来很正确,带有一个制表符,那么为什么不使用它呢?仅用于需要更多字节填充字符串的刑法语言吗?
泰特斯(Titus)

Answers:


3

05AB1E89 87字节

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

召唤克苏鲁编码。使用CP-1252编码。在线尝试!


14

使用Javascript(ES6),165个 161字节

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`
`

编辑:+1个字节来满足“无选项卡”规则

例子

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"));


您可以通过重新排列数组(并可能从字符串中分离数字)来获得一些字节。+1这个想法。
泰特斯(Titus)

@Titus-我必须承认我看不到节省一些字节的重新排列。同样,数字必须被视为字符串,以便replace()可以在不强制的情况下对其进行操作。但是我可能会错过你的意思。
Arnauld

@Titus- 'User3Group68Others58None576Read48Write476Execute475and4576only'.split(/(\d+)/)可能有用。那是你的想法吗?
Arnauld

我误会了他们;认为它们是八进制值。:)但是您的新想法也不错。
泰特斯(Titus)2016年

挑战输出需要空格而不是当前编写的制表符。
Mwr247 '16

13

GNU sed的,187 163 158(157 + 1)个字节

使用-r(ERE regexp)运行。文件不包含尾随换行符。

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

不错的方法,但是在添加and或时,删除数字可以节省大约20个字节only
尼尔,2013年

@Neil那里:)结合了您的建议,可以节省很多。
FireFly

1
第一行可能只是:s/(.)(.)/User: \1\nGroup: \2\nOthers: /。通过移植到具有\d和的Perl可以节省更多的字节\K
ninjalj 2016年

@ninjalj好点。因为我不了解Perl,所以我会坚持使用sed,而且我敢肯定还有其他技巧可以使它变得更短,而不是s ///替代品。
FireFly

6

C#214字节

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

果冻100 91 85 字节

几乎可以肯定是可打高尔夫球的-91字节,什么? 8个月6个智慧字节!
-1.更多的字符串压缩;
-2.由于索引是模块化的,因此将原始后减量减少48。
-3.使用更好的默认链接)。

-9个字节,@ Lynn为我提供了字符串压缩的帮助

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

TryItOnline上进行测试

怎么样?

,“£ɱ~» - 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

八度,185字节

@(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})

创建将输入作为字符串的匿名函数:“ 042”。将其转换为数组:(56-'042)' = [0 4 2]。将此作为多个单元格索引来使用索引单元格数组Read Write and Execute','Read and Write', ...。用途fprintf输出三根弦,以适当的类别:User:Group:Others:

我试图找到一种方法来存储ExecuteWriteRead如需要,但是这竟然超过了天真的做法不同的词并连接。

例子:

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

在线尝试。


2
您可以使用strsplit('Read Write and Execute*Read and Write*Read and Execute*Read only*Write and Execute*Write only*Execute only*None','*')而不是单元格数组文字来保存一些字节
Luis Mendo

4

PowerShell v2 +,189168字节

[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]]}

$args[0]char-array 循环输入。每次迭代时,我们都使用一个数组$i++(默认为0)来选择一个索引,以选择UserGroupOthers,将其与冒号和一个制表符连接,然后将其与另一个数组索引连接。

这是魔术。我们将隐式转换char为an int并减去48(即,将ASCII 48"0")转换为0),选择适当的措词作为ints 的数组。该数组随后用作该'None','Read','Write','Execute','only','and'数组的索引。由于默认$ofs(输出字段分隔符)为空格,因此在进行字符串化时(在其连接到左侧时会发生这种情况),可以在数组元素之间正确插入空格。

这三个字符串留在管道上,并Write-Output在程序完成时通过隐式输出。

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

3

秸秆,193字节

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

在线尝试

在第一个堆栈上压入3次转换表,切换到第二个堆栈,使用对话表转换每个数字并打印。


2

Haskell,186字节

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

例:

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

仅使用前奏。我这样做对吗?

取消高尔夫:

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字节

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])]

如果Execute或Write在行的末尾,则留一个尾随空格,但我没有看到不允许这样做。

编辑通过将range(3)更改为0,1,2,并在我的Linux笔记本电脑上而不是Windows笔记本电脑上检查字节数,节省了5个字节(\ n = \ r \ n或相反。我不记得哪个)。


2

Python 2中,240个 239 238 237 228字节

我以为我最终会放弃这件冷酷的高尔夫球。希望允许尾随空格。(已修复,并在此过程中保存了一个字节)

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

欢迎使用PPCG,这是一个不错的第一答案!
ETHproductions 2013年

阅读完您的代码后,我无耻地将Python 2答案中的range(3)替换为0,1,2。好答案。+1
ElPedro

2

PHP,169个 159字节

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]," ";}

将字符串作为命令行参数:php -r '<code>' <argument>
输出前导换行符而不是尾随换行符

感谢Jörg指出我的错误-并感谢\t

PHP,169字节

具有新的限制:(禁止使用制表符)

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];}

这比with短1字节str_pad,因为它需要额外的空白。

分解

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
}

要为创建数组$n,请使用以下命令:

$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(['User','Group','Others'] as $ i => $ u){echo“ \\ n $ u:\\ t”; 节省一些字节和输出3,4,6是错误的
约尔格Hülsermann

1
这是正确的顺序[5,33,34,66,35,67,131,531]好主意
约尔格Hülsermann

我已经忘了“用户”以用户为exmple节省您想击败的JavaScript在接下来的6个字节做到这一点
约尔格Hülsermann

@JörgHülsermann:无论如何我还是要采用“ \ t”;谢谢。为此+1 :)敬请注意33
泰特斯(Titus)2013年

1
346我们输出的用户:读取和写入组:只执行其他:写和执行它应该网友:写和执行组:只读其他:读,写
约尔格Hülsermann

2

重击- 221 213字节

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]}";}

尚不清楚是否可以将其进一步压缩,至少不能不从根本上改变此处的方法(拆分输入并将其用作${b}保存相应字符串的数组的索引)。


1
\ only扩展的内联代码更短。grep -o .<<<$1比短echo $1|grep -o .,但是从stdin中读取输入while read -n1 c则更好。数组索引在bash中具有算术上下文,因此${l[z++]}有效。l会以字符串的形式缩短,可以通过${l:z++*8:8}(偏移和长度具有算术上下文)进行访问。可以通过读取c,扩展“ User:”,...的内联模式并内联并明智地使用参数扩展来转换另一个字节。
ninjalj

1
对于以下结果:(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}]}"用文字换行符替换\ n)。
ninjalj 2016年

1

Java 7中,300个 284字节

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";}

现在的直接方法。将尝试提出一种更通用的方法来重用单词。

非高尔夫球和测试用例:

在这里尝试。

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"));
  }
}

输出:

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字节

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])}}

松散:

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个字节

{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}&

一个简单的实现(可能很容易打败):不计算任何东西,仅对每个可能的输出进行硬编码。输入是整数;输出每行带有尾随空格和整体尾随换行符。

IntegerDigits[#,10,3]给出输入的三位数(即使有前导零)。每个数字表示“函数”的自变量

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

其中0表示函数名称本身。""<>连接列表中的所有字符串。"\n"&~Array~3产生三个换行符。


我只是注意到,即使使用相同的变量名,我的Python 2答案也几乎与您的答案相同。老实说,我发布之前没见过你的!
ElPedro '16

1
别担心!我认为在这种情况下,变量名的匹配几乎是可以预期的:)
Greg Martin

猜猜你是对的。变量名有点可预测
☺– ElPedro

顺便说一句,我们以同样的方式认为+1 cos :-)
ElPedro

1
顺便说一句,我不知道Mathematica,但我认为您可以通过删除“ only”中的空格来丢失一个字节。它总是在一行的末尾,因此不需要尾随空格。
ElPedro '16

1

Java 7,278

打高尔夫球:

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;}

取消高尔夫:

  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;
  }

输出:

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

蟒3.5,3.6 - 235个 232 228 216字节

(应该适用于所有Python 3.x)

因此,此处的输入位于STDIN上(保存导入☺)。

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")

利用元组,在可能的情况下省略空格,并在通常情况下使用括号将您的意图弄清楚,然后忽略运算符的优先级。

用法示例:

$ 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

未打高尔夫球:

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

批处理,280字节

@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

对字符串进行硬编码比尝试将它们组合在一起要短47字节。如果制表符合法,则将是267个字节。


1

C#307 241 210个字节

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])));}

格式化的

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#,322337348字节

肯定不是最短的版本,但是我尝试使用按位运算符解决此问题,因为这些chmod值实际上是位标志。另外C#可能不是最好的高尔夫语言: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')));}

取消高尔夫:(带有评论)

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
}

这是我第一次打高尔夫球,所以如果我做错了什么,请告诉我:)

编辑1:

通过用(最后)替换s[i]-'0'来保存一些字节,并将s[i]&7列表计数保存到变量中:

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)));}

编辑2:

更改为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字节

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]]}

多亏了达达,节省了20个字节!


3
我可能会弄错,但是您的数组不应该以相反的顺序吗?如果我调用b(“ 000”),它会返回“ Read Write and Execute”,而人们可能会期望“ None” ...
Dada

而且我很确定这可以打得更好。例如,一个191字节的版本: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]]}
达达

1

Visual Basic,606字节

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
欢迎来到PPCG!顺便说一句好吧顺便说一句:)
Beta Decay

1

水晶,200个 194字节

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

返回给定八进制序列的结果字符串作为字符串。例如:m("670")结果至:User: Read and Write\nGroup: Read Write and Execute\nOthers: None

在线尝试


0

C#,371个字节

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
这是代码高尔夫球,因此您必须打高尔夫球。另外,添加带有语言名称和字节数的标头。
TuxCrafting

我添加了您的字节数,即您的分数。您需要使自己的得分尽可能低才能获胜
Beta Decay

例如,您摆脱了每个函数的所有不必要的空格
Beta Decay

1
@BetaDecay谢谢,我是这个社区的新手,我想我最好使用php代替,因为它可能导致更多紧凑代码。
Alireza Tabatabaeian

1
@Alireza这是一个好主意。尽管在此站点上,我们确实希望看到Java和C#的简短答案:)
Beta Decay

0

Python的3.5 - 370个 294 243字节

打高尔夫球:

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])

尺寸检查:

$ du -b OctalToHuman.py 
243     OctalToHuman.py

未打高尔夫球:

#!/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])

样本输出:

$ 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

对于获胜标准来说,这并不是一个真正的竞争者。我们要求所有答案认真尝试以优化其获胜标准的分数(例如,在诸如此类的代码高尔夫挑战中,提交者必须认真尝试以最小化程序的字节数)。
Mego 2016年

您可以删除import sys,并将程序设为匿名函数(lambda o:...),从而节省大量字节。
NoOneIsHere16年

0

F#,204个 203字节

我的第一个高尔夫,所以请您原谅任何错误;)
高尔夫版本(基于pinkfloydx33的回答 1:1 ):

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

非高尔夫版本:

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

用法示例:

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

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


这仅是为了检查我是否可以“改善” pinkfloydx33的答案 -我对该算法不表示任何赞赏


0

PHP,199字节

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字节(\ 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);}

嘿,您应该使用空格而不是制表符
Beta Decay

在这种情况下,\ t看起来像str_repeat(“”,3- $ i)或str_pad(“”,3- $ i,“”),但我的想法无关紧要,我没有机会获胜。另一个空间cs.tut.fi/~jkorpela/chars/spaces.html
约尔格Hülsermann

1
保存13 + 34个字节。在长版本中:使用echo str_pad("$u:",8)代替echo"$u:".str_repeat(" ",3-$i)(-9);这将使$i=>过时(-4)。在两个版本中:使用$a[$z-1]="and $a[$z-1]";代替{$a[]=$a[$z-1];$a[$z-1]="and";}(-7)和else$a[]=$a?Only:None;代替elseif($z<1)$a[]=None;else$a[]=Only;(-14)。转if(1<$z=count($a))$a[$z-1]="and $a[$z-1]";else$a[]=$a?Only:None;if($x=array_pop($a))$a[]=$a?"and $x":"$x Only";else$a[]=None;(-3),然后进入$a[]=($x=array_pop($a))?$a?"and $x":"$x Only":None;(-10)
泰特斯

@Titus echo str_pad(“ $ u:”,8),$ a [$ z-1] =“和$ a [$ z-1]” ;,否则$ a [] = $ a?Only:None; 完成$ i =>作废我不能做,那么$ m = $ argv [1] [$ i]是必要的。其余的我会先尝试另一种方式。谢谢你的输入
约尔格Hülsermann

1
更多建议:if(4&$m=$argv[1][$i])代替$m=$argv[1][$i];if(4&$m)(-3)$m=;if();if();if();用循环替换:foreach([Read,Write,Execute]as$k=>$s)if($argv[1][$i]&4>>$k)$a[]=$s;(-7)
Titus

0

Python 3,191个字节

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])

不打高尔夫球

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
欢迎来到PPCG!不错的第一篇文章!
Rɪᴋᴇʀ

嗯,我很好奇当我只得到191时,主持人是如何获得151字节的:D是错误的吗?检查编辑
Aleksandr Smirnov

那是我,对不起。我在编辑中打错了字。立即修复。
Rɪᴋᴇʀ

0

Javascript(ES6),159个字节

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]]

例:

(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")
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.