高尔夫我的莎士比亚报价参考


45

在为莎士比亚撰写论文时,我意识到我需要将引用引用缩短到更易于管理的长度。我以前一直在写这个:

(Act 1, Scene 2, Lines 345-346)

但是现在我被告知要这样写它们:

(I.ii.345-6)

显然,我需要一些打高尔夫的代码才能对莎士比亚的报价引用有所了解。

任务

编写一个程序或函数,给定在模板1或2之后输入字符串的情况,分别打印或返回在模板3或4之后返回的字符串。您只需要支持Act 1至5和Scene 1至9。

范本

范本1

(Act x, Scene y, Lines a-b)

您可以假设x从不超过5,y从不超过9,a并且b始终是正整数,不超过您语言的最大正标准整数值,并且a始终排他地小于b

范本2

(Act x, Scene y, Line a)

与模板1的条件相同,但有关的信息除外b

范本3

(x.y.a-b)

其中x是大写罗马数字,y是小写罗马数字,a并且b是数字,并且b被缩短为仅小于与相等的第一个不同有效位的数字a

范本4

(x.y.a)

与模板3的条件相同,但不包含有关的信息b

测试用例

让它f(s)成为任务中定义的功能。""表示字符串值。

>>> f("(Act 1, Scene 2, Lines 345-346)")
"(I.ii.345-6)"

>>> f("(Act 3, Scene 4, Lines 34-349)")
"(III.iv.34-349)"

>>> f("(Act 5, Scene 9, Lines 123-234)")
"(V.ix.123-234)"

>>> f("(Act 3, Scene 4, Line 72)")
"(III.iv.72)"

>>> f("(Act 2, Scene 3, Lines 123-133)")
"(II.iii.123-33)"

>>> f("(Act 4, Scene 8, Lines 124-133)")
"(IV.viii.124-33)"

出于这一挑战的目的,必须支持以下阿拉伯到罗马数字的翻译:

1 i     I
2 ii    II
3 iii   III
4 iv    IV
5 v     V
6 vi    (you do not have to support past 5)
7 vii
8 viii
9 ix

是否允许文本文件?

21
我真的希望在SPL中找到答案。
L3viathan '17

5
测试案例:(Act 1, Scene 2, Lines 345-3499)
dzaima '17

11
谁在莎士比亚寻求答案?
泰特斯

1
@Grimy固定#1,#2好吗?
艾迪生·克伦普

Answers:


12

莎士比亚编程语言(非竞争性)

我真的很喜欢这个问题,由于莎士比亚语言的回答有些 兴趣,所以这里是一个。

A Tale of Two Cites (sic).

Julius Caesar, the first citizen of the Roman Republic.
Brutus, a traitor -- member of the Fifth Column.
Cicero, the greatest Roman orator.
Cleopatra, a proud queen, whom the Romans want to make one of their own.
Romeo, a man who's sometimes there.
Juliet, a maiden who can follow Romeo or stand on her own.


           Act I: Imperium Romanum.


           Scene I: Cleopatra puts men in their place.

[Enter Cleopatra and Julius Caesar]

Julius Caesar:
    Thou art as lovely as the sum of an amazing delicious gentle blossoming warm angel and a charming noble reddest rose.
    Speak your mind. Open your mind. Open your mind. Open your mind! Open your mind!

Cleopatra:
    You are as stuffed as the sum of a hard old green horse and the sum of a grandmother and
    a normal tiny bottomless furry small purple roman.

[Exit Julius Caesar]
[Enter Brutus]

Cleopatra:
    You are as sorry as the difference between a rich morning and a leech.
    You are as smelly as the difference between yourself and a sunny rural blue bold uncle.
    You are as vile as the difference between Julius Caesar and yourself.

[Exit Brutus]
[Enter Cicero]

Cleopatra:
    You are as half-witted as the difference between Brutus and the bluest death.


           Scene II: How do you solve a problem like Cleopatra?

[Exeunt]
[Enter Cleopatra and Julius Caesar]

Julius Caesar:
    Listen to your heart!

[Exit Cleopatra]
[Enter Brutus]

Julius Caesar:
    Is Cleopatra more pretty than a fair charming noble angel?

Brutus:
    If so, we must proceed to Scene IV. Is Cleopatra not worse than the sweetest small aunt?

Julius Caesar:
    If so, let us proceed to Scene III.

Brutus:
    Speak your mind.

Julius Caesar:
    Is Cleopatra nicer than the moon?

Brutus:
    If so, speak your mind.

Julius Caesar:
    Is Cleopatra better than a golden King?

Brutus:
    If so, speak your mind.

Julius Caesar:
    We shall proceed to Scene V.


          Scene III: Brutus and his friends.
Julius Caesar:
    Is Cleopatra as fair as the blossoming smooth sky?

Brutus:
    If so, speak your mind!

Julius Caesar:
    Speak your mind!

Julius Caesar:
    Is Cleopatra jollier than the sum of a yellow sweet road and a summer's day?

Brutus:
    If so, speak your mind!

Julius Caesar:
    Is Cleopatra friendlier than the sum of a sweet large angel and a white cow?

Brutus:
    If so, speak your mind!

Julius Caesar:
    Is Cleopatra as furry as a rich handsome huge mistletoe?

Brutus:
    If so, speak your mind!

Julius Caesar:
    We shall proceed to Scene V.


          Scene IV: Cicero is asked to speak.
[Exit Brutus]
[Enter Cicero]

Julius Caesar:
    Is Cleopatra as beautiful as the sum of a small furry white angel and a summer's day?

Cicero:
    If so, speak your mind!

Julius Caesar:
    Speak YOUR mind!


          Scene V: A period piece -- Cleopatra's reprisal.
[Exeunt]
[Enter Cleopatra and Julius Caesar]

Julius Caesar:
    You are as beautiful as the sum of a embroidered sweetest sunny delicious trustworthy Lord
    and a reddest charming mighty honest King.
    You are as healthy as the difference between yourself and a embroidered Lord. Speak your mind!
    Open your mind! Open your mind! Open your mind! Open your mind! Open your mind! Open your mind!

Cleopatra:
    Are you jollier than the sum of a little rural white bottomless blue blue sky and a rural furry white green old morning?

Julius Caesar:
    If so, we must proceed to Act II. Open your mind! Open your mind!

Cleopatra:
    You are as damned as the difference between yourself and a half-witted dusty snotty rotten oozing death.

[Exit Julius Caesar]
[Enter Brutus]

Cleopatra:
    You are as rotten as the difference between yourself and a rural rotten bottomless evil miserable famine.

[Exit Brutus]
[Enter Cicero]

Cleopatra:
    You are as fatherless as the difference between Brutus and a normal pig. Let us return to Scene II.



          Act II: Lovers' arithmetick.

          Scene I: Our lovers discuss what they have in common.

[Exeunt]
[Enter Romeo and Juliet]

Romeo:
    Thou art as bold as a curse. Listen to your heart!

Juliet:
    Am I better than nothing? If so, let us proceed to Scene III.

Romeo:
    Open your mind. Open your mind.

Juliet:
    Listen to your heart! Open your heart!

Romeo:
    Thou art as amazing as the product of the difference between a handsome white proud white grandfather and an aunt
    and the sum of a loving niece and the Heaven. Speak your mind! Open your mind.
    Listen to your heart. Is the quotient between yourself and the sum of the sum of
    a noble noble mighty blossoming embroidered good father
    and a gentle large large normal old joy and an old happy squirrel as yellow as the quotient between
    myself and the sum of the sum of a pretty beautiful yellow green bold charming kingdom and
    a beautiful blue normal cute large nephew and a pretty big cousin?

Juliet:
    If not, we shall proceed to Scene II.

Romeo:
    You are as sweet as the remainder of the quotient between yourself and the sum of the sum of
    a blossoming bottomless golden peaceful noble healthy nose and
    a happy honest sunny green healthy hero and a hard blue fellow.

Juliet:
    YOU are as sweet as the remainder of the quotient between yourself and the sum of the sum of
    a blossoming bottomless golden peaceful noble healthy nose and
    a happy honest sunny green healthy hero and a hard blue fellow.


          Scene II: Tense times.
Juliet:
    Is the quotient between yourself and the sum of a good beautiful delicious grandmother
    and a noble wind as amazing as the quotient between myself and the sum of
    a smooth furry embroidered roman and a honest sister?

Romeo:
    If so, you are as amazing as the remainder of the quotient between
    yourself and the sum of a cute healthy smooth kingdom and a normal mother.


          Scene III: Parting is such sweet sorrow.
Romeo:
    Open your heart! You are as noble as the sum of a honest charming smooth peaceful fine rose and the sum of
    a cute amazing trustworthy summer's day and an angel. Speak your mind!

(它的长度超过6000个字节。)其中有一些技巧,但我并没有尝试打很多高尔夫,因为:(1)我已经在另一个答案上贡献了自己的高尔夫份额,以及(2)将所有字符更改为“页面”和“ Puck”(或所有“ big big big big big cat”的所有短语)似乎破坏了乐趣。在处理罗马数字的部分中,我使用了罗马字符等字符。我确实重用了字符和指令以节省一些键入内容。:-)

该程序应该主要是简单易懂的,但值得一提的是,当我写这篇文章时,我假设读取整数将像 scanf:(1)仅消耗与整数对应的输入字符,以及(2)如果失败,则变量保持不变。(我通过第二个属性来读取第二行中的模板1和模板2,方法是读取“行”并尝试读取整数。)不幸的是,事实证明,(我认为)的原始实现存在一个错误。读取整数的语言会消耗掉直到行尾的所有内容,如果失败则抛出错误,因此它需要修补程序libspl.c才能使int_input行为更像scanf

这样,它可以工作:

% spl2c < good.spl > good.c
% gcc -lspl -o good good.c                                    
% for f in in-*; do cat $f; echo "->"; ./good < $f; echo "\n"; done    
(Act 1, Scene 2, Lines 345-346)
->
(I.ii.345-6)

(Act 3, Scene 4, Lines 34-349)
->
(III.iv.34-349)

(Act 5, Scene 9, Lines 123-234)
->
(V.ix.123-234)

(Act 3, Scene 4, Line 72)
->
(III.iv.72)

(Act 2, Scene 3, Lines 123-133)
->
(II.iii.123-33)

(Act 4, Scene 8, Lines 124-133)
->
(IV.viii.124-33)

我使用的略高级别的伪代码,可帮助尝试理解的任何人:

Print `(`=40
Read 5 chars
Read Int A
Output A in Roman
Output `.`=46
Read 8 chars
Read Int S
Output S in roman
Output `.`=46
Read 6 chars
Set N to -1
Read Int N
If N ≠ -1 goto finish
Read 2 chars
Read Int M
Output Int M
Output `-`=45
Read 1 char
Read Int N
Reduce N wrt M
finish:
Output N
Print `)`=41

上面的内容与最终代码相关联,作为练习。:-)请注意,ShakespearePL具有算术,堆栈和gotos,但没有指针(只有标签),因此实现“子例程”(如转换为Roman)有点有趣。


哇好漂亮 谢谢!:)
史蒂夫·贝内特

1
反复拍打upvote按钮
Addison Crump

9

乳胶,513 364 259 226 215 178 159个字节

好的论文应该总是用LaTeX编写。

\documentclass{tui}\makeatletter\input{xstring}\def~#1 #2, #3 #4, #5 #6){(\@Roman#2.\@roman#4.\StrCut{#6}-\A\B\A\if\B\else-\fi\StrCompare\A\B[\P]\StrMid\B\P9)}

之所以使用xstring包,是因为内置的字符串处理不多。从正面来看,内置\Roman格式的上限比我们需要的更大(甚至十四行诗)2^31-1。我已包括\documentclass{ecv}在内,但没有测试代码:

\begin{document}
\t(Act 1, Scene 2, Lines 345-346) 

\t(Act 3, Scene 4, Lines 34-349)

\t(Act 5, Scene 9, Lines 123-234)

\t(Act 3, Scene 4, Line 72)

\t(Act 2, Scene 3, Lines 123-133)

\t(Act 4, Scene 8, Lines 124-133)
\end{document}

(如果您疯狂到足以实际使用它,则必须至少取消使用宏名称。覆盖单字符宏是一种不好的做法)

取消评论并评论:

\documentclass{ecv}%We have to have a documentclass
\makeatletter %treat the @ sign as a normal character (it's used in "internal" macro names)
\input{xstring} %use the xstring package
\def\shortref#1 #2, #3 #4, #5 #6){ %macro with 6 positional arguments searated by spaces and commas 
    (%print the open bracket
    \@Roman#2 %arg 2 is the Act,  print uppercase Roman
    .%print the full stop
    \roman#4 %arg 4 is the Scene, lowercase roman
    .%print the full stop
    \StrCut{#6}{-}{\A}{\B}%split arg 6 (Lines) at the hyphen, into macros \A and \B
    \A %print the bit before the hyphen
    \ifx\B\empty%if \B has nothing in it do nothing
    \else %otherwise
        - %we need to print a hyphen
    \fi%endif
    \StrCompare{\A}{\B}[\P] %returns (in macro \P) the position at which \A and \B first differ
    \StrMid{\B}{\P}{9}%print \B starting from position \P (9 > the number of remaining characters)
)}%print the closing bracket

请注意,在此版本中,注释是必需的,否则换行符将被解释为空格并扩展为空格。


您可以使用~宏名称(而不是)节省三个字节\s。但是实际上,您根本不需要\s\stripcomma在非高尔夫版本中):您可以,\def\t#1 #2, #3 #4, #5 #6而TeX会负责剥离逗号。(所以你可以使用~的伎俩\t,而不是节省1个字节)
ShreevatsaR

@ShreevatsaR谢谢。您已经弄清楚了如何内联逗号拒绝,它比我尝试过的任何操作都要简单。主动的技巧~有点讨厌,但我在这里喜欢。这意味着我必须更改documentclass(更改为.cls我已安装的其他三个字母文件之一)
Chris H,

1
是的,我数了182个字节,不仅超过了Python的答案,也超过了Ruby,PHP和Perl的答案之一:-)
ShreevatsaR

1
@ShreevatsaR更好:178,\@roman 并且\@Roman不需要在参数周围加括号。
克里斯·H

1
所有主要的xstring想法都是你的:-)一起打高尔夫球真是有趣!
ShreevatsaR

8

JavaScript的(ES6),210个 183 178 177 171字节

通过展开其余参数节省了27个字节(由于ETHproductions

通过不匹配开头括号和调整罗马数字生成来节省5个字节

通过调整最终三元表达式节省了1个字节

通过组合两个匹配的组节省6个字节

s=>s.replace(/Act (\d)\D*(\d)\D*(\d*)(\d*-?)\3(\d*)/,(_,a,b,c,d,e)=>'IIIV'.slice(a>3&&a-2,a)+'.'+'iiiviiix'.slice('233336'[b-4],b-(b>4))+'.'+c+d+(d.length>e.length?e:c+e))

测试用例:

let f = s=>s.replace(/Act (\d)\D*(\d)\D*(\d*)(\d*-?)\3(\d*)/,(_,a,b,c,d,e)=>'IIIV'.slice(a>3&&a-2,a)+'.'+'iiiviiix'.slice('233336'[b-4],b-(b>4))+'.'+c+d+(d.length>e.length?e:c+e))

;[
  ["(Act 1, Scene 2, Lines 345-346)", "(I.ii.345-6)"],
  ["(Act 3, Scene 4, Lines 34-349)", "(III.iv.34-349)"],
  ["(Act 5, Scene 9, Lines 123-234)", "(V.ix.123-234)"],
  ["(Act 3, Scene 4, Line 72)", "(III.iv.72)"],
  ["(Act 2, Scene 3, Line 123-133)", "(II.iii.123-33)"],
  ["(Act 4, Scene 8, Line 124-133)", "(IV.viii.124-33)"],
  ["(Act 1, Scene 2, Lines 345-3499)", "(I.ii.345-3499)"]
].map(([a,b]) => console.log(`${a} => ${f(a)} (${f(a) == b ? 'Pass' : 'Fail'})`))
.as-console-wrapper { min-height: 100% }


我现在不能测试,但如果更换它仍然可以工作Act ,并且每个\D*.*
帕特里克·罗伯茨

它可能; 我很犹豫尝试一下,因为JavaScript默认情况下采用贪婪匹配。我将在今天晚些时候对其进行测试,并让您知道它是否有效。
gyre's

8

果冻 87 86  85 字节

DµU=/œr1LCṫ@Ṫ
Ṗ,Çj”-µ⁸L’$?W
⁾-,yḲḊm2Ṗ€Vµ“¬Q:’ṃ⁾IV;”X“¤|ʂ’BṚ¤œṗị@µ1,2¦Œl2¦µ;ṪÇ$“(..)”ż

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

怎么样?

DµU=/œr1LCṫ@Ṫ - Link 1, toPageShort: list of numbers [fromPage, toPage]  e.g.  [345,365]
D             - cast to decimal lists                                 [[3,4,5],[3,6,5]]
 µ            - monadic chain separation (call that d)
  U           - reverse each                                          [[5,4,3],[5,6,3]]
   =/         - reduce by equality                                              [1,0,1]
     œr1      - strip any 1s from the right                                       [1,0]
        L     - length                                                                2
         C    - complement (1-z)                                                     -1
            Ṫ - tail d                                                          [3,6,5]
          ṫ@  - tail from index (swap @rguments)                                  [6,5]

Ṗ,Çj”-µ⁸L’$?W - Link 2, format page number(s): number or list of two numbers
           ?  - if:
          $   -   last two links as a monad:
        L     -     length
         ’    -     decremented (0 for a number, 1 for a list of two numbers)
      µ       - then:
Ṗ             -   pop (list without the last item, i.e. just the from page)
  Ç           -   call the last link (1) as a monad with the list as its argument
 ,            -   pair
    ”-        -   literal '-'
   j          -   join
              - else:
       ⁸      -   link's left argument (the single page number)
            W - wrap the result in a list (for ease of post-formatting in Main)

⁾-,yḲḊm2Ṗ€Vµ ... µ1,2¦Œl2¦µ;ṪÇ$“(..)”ż - Main link: string s
⁾-,                                    - literal ['-',',']
   y                                   - map (change '-' to ',')
    Ḳ                                  - split at spaces
     Ḋ                                 - dequeue (get all but 1st)
      m2                               - mod-index-2 (1st,3rd,5th)
        Ṗ€                             - pop €ach (ditch last char)
          V                            - evaluate - list of numbers
                                       -   either [act,scene,page] or
                                       -   [act,scene,[from,to]]
           µ     µ   ¦                 - apply to indexes:
                  1,2                  - [1,2]
             ...                       -   see monadic chain " ... ", below
                        2¦             - apply to index 2:
                      Œl               -   lowercase
                          µ            - monadic chain separation
                              $        - last 2 links as a monad:
                            Ṫ          -   tail (page(s))
                             Ç         -   call last link (2) as a monad
                           ;           - concatenate
                               “(..)”  - literal ['(','.','.',')']
                                     ż - zip together
                                       - implicit print

“¬Q:’ṃ⁾IV;”X“¤|ʂ’BṚ¤œṗị@ - monadic chain " ... " from Main
                         -   Get Roman numeral: number n (n>0, n<10) (act or scene)
“¬Q:’                    - base 250 literal 520559
      ⁾IV                - literal ['I','V']
     ṃ                   - base decompression -> "IIIIIIIVVVIVIIVIIII"
          ”X             - literal 'X'
         ;               - concatenate -> "IIIIIIIVVVIVIIVIIIIX"
                   ¤     - nilad followed by link(s) as a nilad:
            “¤|ʂ’        -   base 250 literal 281418
                 B       -   convert to a binary list
                  Ṛ      -   reverse
                    œṗ   -   split at truthy indexes i.e: I II III IV V VI VII VIII IX
                      ị@ -   index into (swap @arguments) using n

1
这一定是Jelly脚本的某种记录
MickyT '17

@MickyT不,我已经不在那了……
乔纳森·艾伦

这引起头痛。不要读0/10。:P
暴民埃里克(Erik the Outgolfer)'17

@EriktheOutgolfer抱歉!
乔纳森·艾伦

2
言归正传,我能看到一些真正独特的东西,在那个代码,例如œrṖ,ÇṖ€VṪÇ$W作为一个辅助链路上的最后一个环节,可能还有其他人也一样,很好的努力!这不是您通常使用的80左右的果冻糖,这在果冻糖中值得特别认可。
暴民埃里克'17

6

[R 94 126 112 166字节

现在,它比以前的单词:(,回到尝试进一步打高尔夫球。正则表达式用于减少无耻被盗的页面引用复杂。Regex从@FryAmTheEggman借来的。

现在,我确实需要做一些工作来取回字节,但是现在它适用于第二种情况。

R=as.roman;i=sub(',','',scan(,''));sprintf('(%s.%s.%s',R(i[2]),tolower(R(i[4])),`if`(!diff(c(nchar(el(strsplit(i[6],'-'))),0))-1,sub('((.+).*-)\\2','\\1',i[6]),i[6]))

在线尝试!-请注意,这el不适用于TIO,已被替换为unlist

R=as.roman;                              # Used to convert to roman numeral class
i=sub(',','',scan(,''));                 # Get input, splits on spaces, remove ,'s
sprintf('(%s.%s.%s',                     # Use sprintf to format the output.
    R(i[2]),                             # Convert to roman numeral
    tolower(R(i[4])),                    # Convert to roman numeral and lowercase
    `if`(                                #
       !diff(                            # Test if the lengths of the last string
       c(nchar(el(strsplit(i[6],'-'))),0)# split on the hyphen are different (extra 0 to appease diff)
       )-1,                              # taking into account the trailing )
       sub('((.+).*-)\\2','\\1',i[6]),   # on true use regex to reduce range
       i[6]                              # else output as is
    )
)

4

视网膜89 88字节

T`, lL`._
2`(\d+)
$*i
i{5}
v
i{4}
iv
viv
ix
1T`l`L`\w+
(\b(.+)(.)*-)\2((?<-3>.)*)\b
$1$4

在线尝试!

感谢Neil,节省了3个字节。

先去除不必要的字符,然后再将前两个数字替换为i字符块。然后,将其匹配i以形成适当的罗马数字。然后,我们将第一个罗马数字大写。最后,我们在连字符之前和之后匹配尽可能多的数字,以使数字中的位数相同。然后,我们从第二个数字中删除该前缀。


更换iiiiiviiiiivvivix,似乎节省了几个字节。
尼尔

但是,您的行号缩短似乎在弄错了,因为345-356我期望如此345-56
尼尔,2017年

@Neil Whoops,忘记了克雷恩扩展。无论如何,感谢小费!
FryAmTheEggman's

您可以\b在最后一次替换的末尾使用以避免重复)替换吗?
尼尔

@Neil我不认为这行得通,因为我认为我需要使用\d它,但由于没有其他单词边界,它似乎确实行得通。谢谢!
FryAmTheEggman's

4

PHP> = 7.1,195字节

preg_match_all("#\d+#",$argn,$t);[[$a,$s,$b,$e]]=$t;for(;$e&&~$c=$e[$k-=1];$p="-".substr($e,$i))$c>$b[$k]&&$i=$k;echo"(",strtoupper(($r=[_,i,ii,iii,iv,v,vi,vii,viii,ix])[$a]),".$r[$s].$b",$p,")";

测试用例

展开式

preg_match_all("#\d+#",$argn,$t); # match for all groups of digits
[[$a,$s,$b,$e]]=$t; # shorter variables names for these groups
for(;$e&&~$c=$e[$k-=1];$p="-".substr($e,$i)) # prepare the seceond line if exists
  $c>$b[$k]&&$i=$k; 
echo"(" # print the char (
,strtoupper(($r=[_,i,ii,iii,iv,v,vi,vii,viii,ix])[$a]) # print the upper roman digit for Act
,".$r[$s].$b" # print the lower roman digit for Scene and the first line with trailing "."
,$p # print shorted second Line
,")"; #Print the closing )

1
preg_match_all("#\d+#",$argn,$m);[$a,$s,$b,$e]=$m[0];保存两个字节。if($e){for(;$b[$i]==$e[$i];$i++);echo"-",substr($e,$i);}echo")";应该节省46。(you do not have to support past 5)节省15个字节。
泰特斯

1
".$r[$s].$b"保存另外5个字节;和[[$a,$s,$b,$e]]=$m;另一个。不幸的是,数组分配还不能按引用进行工作。
泰特斯

if($e&&$e-$b){for($x=str_pad($b,strlen($e),0,0);$x[$i]==$e[$i];$i++);echo"-",substr($e,$i);}保存10个字节,可能会起作用。
泰特斯

对我来说还不错。并且&&$e-$b对于测试用例是不必要的;因此节省了17个字节,而不是10个字节。您仍然不需要罗马6到9 ;;)
泰特斯(Titus

1
您可以替换for(;str_pad($b,strlen($e),0,0)[$i]==$e[$i];)$i++;for(;$e&&~$c=$e[-++$k];)$c>$b[-$k]&&$i=-$k;
克里斯多夫(Christoph)

3

Perl 5,185 + 1 = 186字节

要求的-n标志为1个字节的罚款。

对于某些场景超过10 ^ 11行的测试案例,可能会失败,但是AFAIK no Shakespeare场景的长度相当长;)

y/A-z //d;while($x++<9){s/,(\d+)(\d{$x})-\g1(\d{$x}\))/,$1$2-$3/};@F=split/,/;for($F[0],$F[1]){$_.='i'while(y/2-91/1-8/d);s/i{5}/v/g;s/i{4}/iv/;s/v(i)?v/$1x/;s/$/,/};$F[0]=uc$F[0];say@F

可读形式:

y/A-z //d; #Delete all characters besides numbers, parenthesis, and comma
while($x++<9){s/,(\d+)(\d{$x})-\g1(\d{$x}\))/,$1$2-$3/}; #Shortens the line numbers. Super ugly, but my simpler code broke on test case 2- that fix added 26 bytes :( I'll revisit this later, perhaps...
@F=split/,/; #Splits the input into an array so we can mess with the act and scene without messing with the lines
for($F[0],$F[1]){ #For loop over the act and scene
    $_.='i'while(y/2-91/1-8/d); #Recursively turn numbers into naive Roman numerals (i.e. 9 would be iiiiiiiii)
    s/i{5}/v/g;s/i{4}/iv/;s/v(i)?v/$1x/;s/$/,/ #Substitution rules to convert naive Roman numerals into real Roman numerals and add a comma to the end
}
$F[0]=uc$F[0]; #Convert act to uppercase
say@F #Output

2

红宝石,204 + 1 = 205字节

使用-p标志。

d=[r=%w"i ii iii iv v vi vii viii ix",r.map(&:upcase)]
i=-1
gsub(/\w+ ([\d-]+)/){(a=d.pop)?a[$1.hex]:(a,b=$1.split ?-;b ?(a="%0#{b.size}d"%a;b[0]=""while b[0]==a[i+=1];a.sub(/^0*/){}+?-+b):a)}
gsub", ",?.

在线尝试!


2

Python 2.7 298字节

import re
r=lambda n:'iiiviiix'[2*(n>3)+(n>4)+3*(n>8):n-(n>4)]
o=lambda x,y,n=0:n*(len(x)==len(y))if not x or x[0]!=y[0]else o(x[1:],y[1:],n+1)
q=lambda a,s,g,h:(r(int(a)).upper(),r(int(s)),g+'-'+h[o(g,h):]if h else g)
f=lambda p:'(%s.%s.%s)'%q(*re.match('\D*(\d)\D*(\d)\D*(\d+).(\d*)',p).groups())

2

Perl,99个字节

/(.+)(-\1|.(?2).)\b/;@r=(s/-$1/-/,I,II,III,IV,V,VI,VII,VIII,IX);s/Act(.+)(.,).+ /$r[$1].\L$r[$2]./

用运行perl -pe。98个字节(源)+1个字节(p标志)= 99。


在发布本文时,还有另一个Perl答案(codegolf.stackexchange.com/a/123400/6484),但是它长186个字节,并且使用了截然不同的想法,因此我觉得单独提出一个答案是合适的。
Grimmy

这似乎很浪费,因为它要求提供超过5的罗马数字
Hagen von Eitzen

2
@HagenvonEitzen挑战指定您必须支持最多9个罗马数字。测试用例3具有“场景9”,测试用例6具有“场景8”;测试用例3具有“场景9”。如果我仅支持不超过5的罗马数字,那么两者都将失败。
Grimmy

2

Python 2中301个 259 252 221字节

得益于Chas Brown,它的字节数高达-31个。

所以,嗯,这很长……我想我可以打高尔夫球,但是我已经动了好一阵子了。

import re
def f(s):s,r=re.match(r'.*?(\d),.*?(\d), .*? (\d*)(\d*-?)\3(\d*)',s),'0 i ii iii iv v vi vii viii ix'.split();b,c,d,e,f=s.groups();print'(%s.%s.%s)'%(r[int(b)].upper(),r[int(c)],d+e+(f if len(e)>len(f)else d+f))

在线尝试!

分解

import re                     # re module for regex stuff

def f(s):                     # function that accepts one argument

    s, r = (re.match(r'.*?(\d),.*?(\d), .*? (\d*)(\d*-?)\3(\d*)', s),
           # match the string and capture the important parts using regex

           '0 i ii iii iv v vi vii viii ix'.split()
           # array that stores roman numerals

    b, c, d, e, f = s.groups()
                    # all the numbers from the match to variables

    print '(%s.%s.%s)' % (
                              r[int(b)].upper(),
                              # get the respective roman numeral and make it uppercase

                              r[int(c)],
                              # get the respective roman numeral

                              d + e + (f if len(e) > len(f) else d + f)
                              # shorten the second number if it's shorter than the first number
                         )

您可以通过使用节省一点b,c,d,e,f=s.groups(),而不是a,b,c,d,e,f=[s.group(n) for n in range(6)]
查斯·布朗

和另外5个使用[0]+'i,ii,iii,iv,v,vi,vii,viii,ix'.split(',')代替[s,'i','ii','iii','iv','v','vi','vii','viii','ix']
查斯·布朗

修改-并使用代替来另外8个[0]+'i ii iii iv v vi vii viii ix'.split()[s,'i','ii','iii','iv','v','vi','vii','viii','ix']
Chas Brown

哦,呵呵,不知道你能做到。谢谢!
完全人类

尼斯调整放在0引号里面。我可以看到的最后一个细微调整:您正在使用:s,r=XXX,YYY;b,c,d,e,f=s.groups();您可以节省另外4个字节,而只需等价地说:b,c,d,e,f=XXX.groups();r=YYY;。这样您最终比我提交的文件少81个字节!:)
查斯·布朗

2

Q / KDB +,200个 187字节

解:

f:{R:(($:)N:(!)11)!($:)``i`ii`iii`iv`v`vi`vii`viii`ix`x;S:","vs x inter .Q.n,",-";L:"-"vs P:S 2;"(",("."sv(upper R S 0;R S 1;$[{x[y]=x z}[#:;F:L 0;T:L 1];F,"-",((*:)N(&:)F<>T)_T;P])),")"}

例子:

q)f "(Act 1, Scene 2, Lines 345-346)"
"(I.ii.345-6)"
q)f "(Act 3, Scene 4, Lines 34-349)"
"(III.iv.34-349)"
q)f "(Act 5, Scene 9, Lines 123-234)"
"(V.ix.123-234)"
q)f "(Act 3, Scene 4, Line 72)"
"(III.iv.72)"
q)f "(Act 2, Scene 3, Lines 123-133)"
"(II.iii.123-33)"
q)f "(Act 4, Scene 8, Lines 124-133)"
"(IV.viii.124-33)"

说明:(略有松懈感)

f:{
  // create map of 0->10 to roman numerals, e.g. "5" -> "v"
  R:(($:)N:(!)11)!($:)``i`ii`iii`iv`v`vi`vii`viii`ix`x;
  // remove everything from the input string except -, then split on ,
  S:","vs x inter .Q.n,",-";
  // split the final field on '-', also save final field in variable P
  L:"-"vs P:S 2;
  // if the length of from/to lines are the same then find the first character
  // where they differ, and cut this many characters from the 'to' string
  M:$[{x[y]=x z}[#:;F:L 0;T:L 1];F,"-",((*:)N(&:)F<>T)_T;P];
  // join everything together, use act/scene to index into 
  // the roman numeral map, uppercase the act
  "(",("."sv(upper R S 0;R S 1;M)),")"
  }

笔记:

从技术上讲,它可以短2个字节(不需要f:),但是可以更轻松地以这种方式显示示例。

编辑:

  • -13个字节;更换string$:count#:til(!)first(*:),投R的指数为字符串所以我们没有投行为/场景分为整数
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.