文件权限


26

文件权限

改编自UIL-计算机科学编程免费答案问题“ Carla”,适用于2018年学区。

介绍

在类似UNIX的操作系统中,每个文件,目录或链接均由“用户”“拥有”,该“用户”是“组”的成员,并且具有由十个字符的字符串表示的某些“权限”,例如“ drwxrwxrwx”。第一个字符为“ d”,“-”或“ l”(目录,文件或链接),后跟三组“ rwx”值,表示“读,写,执行”权限。第一组是用户的权限,中间是组的权限,第三组是该对象的其他所有人的权限。

这些权利中的任何一项均被拒绝的许可由“-”代替“ r”,“ w”或“ x”表示。例如,样本目录许可权字符串将为“ drwxr--r--”,指示用户的完整目录权限,但指示组成员和所有其他用户的“只读”权限。

每个“ rwx”组合也可以用八进制值(0-7)表示,其中最高有效位表示读取许可,第二高有效位表示写入许可,最低有效位表示执行许可。

挑战

给定一个由以下四个字符组成的代码字符串:“ D”,“ F”或“ L”,然后是一个三位数的八进制整数值(例如664),输出表示许可值的10个字符串指示。

输入项

您的程序或函数可以从标准输入中读取输入(将输入四个字符,可以选择后面跟换行符),也可以将输入作为参数传递。

您的程序可以接受大写或小写输入,但必须一致(所有输入均为大写或所有输入均为小写)。

输出量

您的程序必须输出结果的十个字符的字符串,该字符串表示以上面指定的确切格式表示的权限值。允许拖尾空格。

测试用例

输入:F664输出:-rw-rw-r--
输入:D775输出:drwxrwxr-x
输入:L334输出:l-wx-wxr--
输入:F530输出:-r-x-wx---
输入:D127输出:d--x-w-rwx

计分和规则


等待什么,昨天问,答案已经接受了吗?这是否意味着不会再有其他答案?
Nit

1
@Nit总是欢迎有更多答案,无论是否接受答案。
isaacg '18

1
@Nit我在移动设备上,试图对不相关的答案进行投票(此后已删除)。我不小心用胖手指按了“接受答案”按钮。我不知道该如何拒绝,所以我将接受的答案更改为最短的答案。
Billylegota '18

2
@Nit我的意思是……他确实接受了丹尼斯的回答,所以他说实话可能是正确的。
魔术章鱼缸

Answers:


7

果冻,19字节

“rwx“-”Œp⁺;Ṁ⁾f-yị@~

在线尝试!

怎么运行的

“rwx“-”Œp⁺;Ṁ⁾f-yị@~  Main link. Argument: s (string)

“rwx“-”              Set the return value to ["rwx, "-"].
       Œp            Take the Cartesian product, yielding ["r-", "w-", "x-"].
         ⁺           Take the Cartesian product, yielding
                     ["rwx", "rw-", "r-x", "r--", "-wx", "-w-", "--x", "---"].
          ;Ṁ         Append the maximum of s (the letter).
            ⁾f-y     Translate 'f' to '-'.
                  ~  Map bitwise NOT over s.
                     This maps the letter to 0, because it cannot be cast to int,
                     and each digit d to ~d = -(d+1).
                ị@   Retrieve the results from the array to the left at the indices
                     calculated to the right.
                     Indexing is modular and 1-based, so the letter from s is at
                     index 0, "---" at index -1, ..., and "rwx" at index -8.

16

bash,59 53字节

chmod ${1:1} a>a;stat -c%A a|sed s/./${1:0:1}/|tr f -

正确的工作工具?

感谢Dennis保存5个字节,并感谢HTNW保存1 个字节。

在线尝试!

chmod ${1:1} a>a;  # call chmod with the input with its first character removed
                   # note that the redirection creates the file a *before* the
                   #   chmod is run, because of the way bash works
stat -c%A a|       # get the human readable access rights
sed s/./${1:0:1}/  # replace the first character with the first char of input
|tr f -            # transliterate, replacing f with -

嗯,那太快了。当然是工作的正确工具。
Billylegota '18

chmod ${1:1} a>a;stat -c%A a|sed "s/-/\L${1:0:1}/;s/f/-/"保存两个字节。
丹尼斯,

@Dennis,我想您可以trychmod ${1:1} a>a;stat -c%A a|sed s/./\\L${1:0:1}/|tr f -
用来

2
假定没有文件a并且用户有权制作文件还是存在文件a并且用户可以写文件是合法的吗?因为如果有一个a拥有root权限的文件700,则这不起作用。
NoOneIsHere

2
@NoOneIsHere虽然讨论中从未特别提出权限,但社区决定默认情况下允许在当前目录创建临时文件。通过扩展,我们可以假设这是可能的。
丹尼斯

10

Python 2,78个字节

lambda a,*b:[a,'-'][a=='f']+''.join('-r'[x/4]+'-w-w'[x/2]+'-x'[x%2]for x in b)

将输入作为一个字符和三个整数。
在线尝试!

说明

[a,'-'][a=='f']接受输入字符或-(如果字符为)f
'-r'[x/4]+'-w-w'[x/2]+'-x'[x%2]本质上是获取rwx字符串的八进制转换。



5

视网膜0.8.2,43字节

\d
$&r$&w$&x
f|[0-3]r|[0145]w|[0246]x
-
\d

在线尝试!链接包括测试用例。以小写形式输入。说明:

\d
$&r$&w$&x

一式三份的每一个数字,与后面添加rwx

f|[0-3]r|[0145]w|[0246]x
-

将所有不正确的字母更改为-s。

\d

删除所有剩余的数字。


4

视网膜,51字节

f
-
0
---
1
--x
2
-w-
3
-wx
4
r--
5
r-x
6
rw-
7
rwx

在线尝试!

不知道如何使用Retina,所以请让我知道如何更好地做。我只是认为我会尝试学习至少一种非Pyth的语言。

说明:

替换f-(保留dl保持不变),然后将各个数字替换为适当的rwx


:/我可以做到这一点,但没有进一步。而且聪明的方法是超级笨拙
仅限ASCII

使用某种三元/逻辑或//加和修剪运算符的人会更富高尔夫精神

@纯ASCII码您的想法非常好,我已将其用于此答案 :)
Leo

4

JavaScript(ES6),63个字节

期望输入字符串为小写。

s=>s.replace(/\d|f/g,c=>1/c?s[c&4]+s[c&2]+s[c&1]:'-',s='-xw-r')

在线尝试!

已评论

s => s.replace(   // replace in the input string s
  /\d|f/g, c =>   //   each character c which is either a digit or the letter 'f'
    1 / c ?       //   if c is a digit:
      s[c & 4] +  //     append '-' or 'r'
      s[c & 2] +  //     append '-' or 'w'
      s[c & 1]    //     append '-' or 'x'
    :             //   else:
      '-',        //     just replace 'f' with '-'
  s = '-xw-r'     //   s holds the permission characters
)                 // end of replace()

4

木炭,27字节

FS≡ιdιlιf¦-⭆rwx⎇§↨⁺⁸Iι²⊕λκ-

在线尝试!链接是详细版本的代码。说明:

 S                          Input string
F                           Loop over characters
   ι                        Current character
  ≡                         Switch
    d                       Literal `d`
     ι                      Implicitly print current character
      l                     Literal `l`
       ι                    Implicitly print current character
        f                   Literal `f`
         ¦                  (Separator between string literals)
          -                 Implicitly print literal `-`
                            Implicit default case
            rwx             Literal `rwx`
           ⭆                Map over characters
                     ι      Input character
                    I       Cast to integer
                   ⁸        Literal 8
                  ⁺         Sum
                      ²     Literal 2
                 ↨          Base conversion
                        λ   Inner index
                       ⊕    Incremented
                §           Index into base conversion
                         κ  Inner character
                          - Literal `-`
               ⎇            Ternary
                            Implicitly print

4

Haskell84 83 81字节

f 'f'='-'
f y=y
t#n=f t:((\x->["-r"!!div x 4,"-w-w"!!div x 2,"-x"!!mod x 2])=<<n)

在线尝试!

最终在概念上与Mnemonic的Python 2答案非常相似。f创建文件类型,其余的是从八进制数获取权限。这真的让我很想念&有点前奏和算子。


2
您可以使用div代替quot
nimi

4

Java 8,100字节

s->s.replaceAll("(\\d)","$1r$1w$1x").replaceAll("f|[0-3]r|[0145]w|[0246]x","-").replaceAll("\\d","")

在线尝试。

@Neil的Retina答案的端口。

说明:

s->                                 // Method with String as both parameter and return-type
  s.replaceAll("(\\d)","$1r$1w$1x") //  Replace every digit `d` with 'drdwdx'
   .replaceAll("f                   //  Replace every "f",
                |[0-3]r             //  every "0r", "1r", "2r", "3r",
                |[0145]w            //  every "0w", "1w", "4w", "5w",
                |[0246]x",          //  and every "0x", "2x", "4x", "6x"
               "-")                 //  with a "-"
   .replaceAll("\\d","")            //  Remove any remaining digits

这很聪明!;)
OlivierGrégoire18年

@OlivierGrégoire好吧,主要是因为它节省了return语句和循环。太可惜的.replaceAll是,三个人的字节数仍然少于带有.replaceAll和添加return和String-array 的循环的字节数。但是,当然值得感谢Neil,我将Retina用作我移植的基础。
凯文·克鲁伊森

3

果冻,21 字节

Ḣ⁾f-yɓOBṫ€4a“rwx”o”-ṭ

完整程序打印到STDOUT。(作为单子链接,返回值是一个包含一个字符的列表和三个字符列表的列表。)

在线尝试!或查看测试套件

怎么样?

Ḣ⁾f-yɓOBṫ€4a“rwx”o”-ṭ | Main Link: list of characters
Ḣ                     | head & pop (get the 1st character and modify the list)
 ⁾f-                  | list of characters = ['f', '-']
    y                 | translate (replacing 'f' with '-'; leaving 'd' and 'l' unaffected)
     ɓ                | (call that X) new dyadic chain: f(modified input; X)
      O               | ordinals ('0'->48, '1'->59, ..., '7'->55 -- notably 32+16+value)
       B              | convert to binary (vectorises) (getting three lists of six 1s and 0s)
        ṫ€4           | tail €ach from index 4 (getting the three least significant bits)
           “rwx”      | list of characters ['r', 'w', 'x']
          a           | logical AND (vectorises) (1s become 'r', 'w', or 'x'; 0s unaffected)
                 ”-   | character '-'
                o     | logical OR (vectorises) (replacing any 0s with '-'s)
                   ṭ  | tack (prepend the character X) 
                      | implicit print (smashes everything together)


3

视网膜,38字节

通过启发评论ASCII唯一

\d
---$&*
---____
r--
--__
w-
-_
x
f
-

在线尝试!

想法是将每个数字转换为一进制(在Retina中默认的一进制数字为_-,并使用三个前导,然后将二进制数字从最高有效位转换为最低有效位。


2

Python 3,71个字节

lambda s:("-"+s)[s[0]!="f"]+stat.filemode(int(s[1:],8))[1:]
import stat

在线尝试!

Python 3.3+内置了此功能,尽管由于需要导入,并且预期的输入格式有所不同,但它对高尔夫并不友好。


2

Tcl,139字节

proc P s {join [lmap c [split $s ""] {expr {[regexp \\d $c]?"[expr $c&4?"r":"-"][expr $c&2?"w":"-"][expr $c&1?"x":"-"]":$c==f?"-":$c}}] ""}

在线尝试!


Tcl,144字节

proc P s {join [lmap c [split $s ""] {expr {[regexp \\d $c]?[list [expr $c&4?"r":"-"][expr $c&2?"w":"-"][expr $c&1?"x":"-"]]:$c==f?"-":$c}}] ""}

在线尝试!

Tcl,149字节

proc P s {join [lmap c [split $s ""] {if [regexp \\d $c] {list [expr $c&4?"r":"-"][expr $c&2?"w":"-"][expr $c&1?"x":"-"]} {expr {$c==f?"-":$c}}}] ""}

在线尝试!

Tcl,150字节

proc P s {join [lmap c [split $s ""] {if [regexp \\d $c] {set v [expr $c&4?"r":"-"][expr $c&2?"w":"-"][expr $c&1?"x":"-"]} {expr {$c==f?"-":$c}}}] ""}

在线尝试!

Tcl,180字节

proc P s {join [lmap c [split $s ""] {if [regexp \\d $c] {[set R regsub] (..)1 [$R (.)1(.) [$R 1(..) [$R -all 0 [format %03b $c] -] r\\1] \\1w\\2] \\1x} {expr {$c==f?"-":$c}}}] ""}

在线尝试!

还是很不满意!


2

Java(JDK 10),118字节

s->{var r=s[0]=='f'?"-":""+s[0];var z="-xw r".split("");for(int i=0;++i<4;)r+=z[s[i]&4]+z[s[i]&2]+z[s[i]&1];return r;}

在线尝试!

学分


2
当你把输入的小写fdl,你可以改变var r=s[0]<70?"d":s[0]<72?"-":"l";,以var r=s[0]=='f'?"-":s[0]+"";保存6个字节。另外,.toCharArray()可以.split("")节省额外的4个字节。
凯文·克鲁伊森

2
@KevinCruijssen您的想法使我节省了13个字节,而不是10个字节(因为我可以删除""+后面的字节,将其“强制char转换” 为String);)谢谢!
奥利维尔·格雷戈雷(OlivierGrégoire)

2

Excel,224个字节

=IF(LEFT(A1,1)="f","-",LEFT(A1,1))&CHOOSE(MID(A1,2,1)+1,"---","--x","-w-","-wx","r--","r-x","rw-","rwx")&CHOOSE(MID(A1,3,1)+1,"---","--x","-w-","-wx","r--","r-x","rw-","rwx")&CHOOSE(MID(A1,4,1)+1,"---","--x","-w-","-wx","r--","r-x","rw-","rwx")

分四个阶段完成:

IF(LEFT(A1,1)="f","-",LEFT(A1,1))    Replace "f" with "-".

和3次:

CHOOSE(MID(A1,2,1)+1,"---","--x","-w-","-wx","r--","r-x","rw-","rwx")

尝试变得更聪明,25 bytes每组权利增加了75种:

IF(INT(MID(A1,2,1))>3,"r","-")&IF(MOD(MID(A1,2,1),4)>1,"w","-")&IF(ISODD(MID(A1,2,1)),"x","-")

2

05AB1E34 27字节

ćls8βbvyi…rwx3*Nèë'-}J'f'-:

在线尝试!

Golfed向下7个字节由@MagicOctopusUrn


ć                           # Remove head from string.
 ls                         # Lowercase swap.
   8βb                      # Octal convert to binary.
      vy                    # For each...
        i        ë  }
         …rwx3*Nè           # If true, push the correct index of rwx.
                  '-        # Else push '-'.
                     J      # Repeatedly join stack inside the loop.
                      'f'-: # Repeatedly replace 'f' with '-' inside the loop.

ćls8βbvyi…rwx3*Nèë'-}J'f'-:对于7少...
魔术八达通瓮城

基本上,使用if语句只是一种不同的排序方式,而不是删除fI而是用替换f最终字符串中的all -
魔术

i <CODE FOR TRUE> ë <CODE FOR FALSE> }
魔术章鱼缸

@MagicOctopusUrn好!
Geno Racklin Asher

1

Python 2,238字节

lambda m,r=str.replace,s=str.split,j="".join,b=bin,i=int,z=str.zfill,g=lambda h,y:y if int(h)else "-":r(m[0],"f","-")+j(j([g(z(s(b(i(x)),"b")[1],3)[0],"r"),g(z(s(b(i(x)),"b")[1],3)[1],"w"),g(z(s(b(i(x)),"b")[1],3)[2],"x")])for x in m[1:])

在线尝试!

我本来以为这是杯水车薪,但是我确实错了。也许应该已经意识到,lambda在某些时候并不是最好的主意。


:| 太多内建函数=太长
仅支持ASCII

1

APL + WIN,55个字节

提示输入字符串的首字母小写:

('dl-'['dlf'⍳↑t]),⎕av[46+(,⍉(3⍴2)⊤⍎¨⍕1↓t←⎕)×9⍴69 74 75]

说明:

9⍴69 74 75 create a vector of ascii character codes for rwx -46, index origin 1

1↓t←⎕ prompt for input and drop first character

,⍉(3⍴2)⊤⍎¨⍕ create a 9 element vector by concatenating the binary representation for each digit 

46+(,⍉(3⍴2)⊤⍎¨⍕1↓t←⎕)×9⍴69 74 75 multiply the two vectors and add 46

⎕av[.....] convert back from ascii code to characters, 46 being '-'

('dl-'['dlf'⍳↑t]), append first character from input swapping '-' for 'f'


1

J57 52字节

感谢FrownyFrog,节省了5个字节!

-&.('-DLld'i.{.),[:,('-',:'rwx'){"0 1&.|:~1#:@}."."0

在线尝试!

另一个长远的解决方案……我不知道如何使用}默认动词,这就是为什么我花了更长的时间{"0 1&.|:进行选择的原因。

说明:

@}. 删除第一个符号,然后

,.&.": 将其余部分转换为十进制数字列表

]:#: 将每个数字转换为二进制数字列表(并覆盖分叉)

('-',:'rwx') 创建一个2行表,并使用0从第一行中选择/ 1-从第二行中选择

   '-',:'rwx'
---
rwx

{"0 1&.|:~ 使用二进制数字从上表中选择

[:, 展平结果

('d-l'{~'DFL'i.{.) 格式化第一个符号

, 将fisrt符号附加到权限列表


1
输入已经是一个字符串,您需要1#:@}."."0
FrownyFrog

1
这似乎可行:('d-l'{~'DFL'i.{.)-&.('-DLld'i.{.)
FrownyFrog

@FrownyFrog很不错的使用i.&.感谢!顺便说一句,您能告诉我如何}在默认动词中使用选择吗?
Galen Ivanov '18

1
2 2 2&#:`('-',:'rwx'"_)}@"."0@}.长度完全相同
FrownyFrog

然而,它并没有中断333:)
FrownyFrog

1

PHP,68字节

<?=strtr(strtr($argn,[f=>_,___,__x,_w_,_wx,r__,r_x,rw_,rwx]),_,"-");

转换f为小写输入下划线和每一个八进制数它的rwx等效,使用下划线代替破折号(保存为报价的需要),然后替换_-

与管道一起运行-nF在线尝试


1

C(gcc)109104字节

至少C可以转换八进制输入。...:-)

编辑:我意识到大小修改器不是严格要求的,并且putchar()printf()本例中的要短!

f(a,b){char*s="-xwr";scanf("%c%o",&a,&b);putchar(a-70?a:*s);for(a=9;~--a;putchar(s[(1&b>>a)*(a%3+1)]));}

在线尝试!

原版的:

f(a,b){char*s="-xwr";scanf("%c%3o",&a,&b);putchar(a-70?a:*s);for(a=9;~--a;printf("%c",s[(1&b>>a)*(a%3+1)]));}

在线尝试!

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.