単語は互いに素ですか?


18

単語が与えられたら、すべての文字を英語のアルファベットの数字として扱い(a1にbなる、2にzなる、26 になる、など)、重複を含むすべてがペアワイズcoprimeであるかどうかを確認します。

入力は、小文字の英語文字の正確に1つの単語です。単語が互いに素である場合の出力は事実です:真/偽の値ですが、それらの2つのバリアントのみです。標準的な抜け穴は禁止されています。

テストケース:

  • manTrue
  • dayTrue(ØrjanJohansenに感謝)
  • ledFalsel=12d=4持っていますgcd=4
  • mana:(複数回発生しTrueますaが、1と1は互いに素です)
  • momFalsegcd(13,13)=13)
  • ofFalse(xnorに感謝しますが15∤6gcd(15,6)=3
  • a:(True文字のペアがない場合は、単語を余素として扱います)

これはなので、バイト単位の最短コードが勝ちです!


1
0それらが互いに素である1場合とそうでない場合に出力できますか?
ディルナン

2
バギー答えをキャッチしていた推奨テスト・ケース:day: True
Ørjanヨハンセン

1
またof: False、値が別の値の倍数ではないという誤った例があることをお勧めします。
xnor

@dylnanいいえ、直感的です。とにかく、デニスの答えは良いです;-)
bodqhrohro

@LuisMendo真実/偽はありますが、2つだけです。
bodqhrohro

回答:



8

ゼリー、10バイト

ØaiⱮgþ`P$Ƒ

オンラインでお試しください!

使い方

ØaiⱮgþ`P$Ƒ  Main link. Argument: s (string)

Øa          Yield "abc...xyz".
  iⱮ        Find the 1-based index of each c of s in "abc...xyz".
        $Ƒ  Call the monadic chain to the left.
            Yield 1 if the result is equal to the argument, 0 if not.
    gþ`       Take the GCDs of all pairs of indices, yielding a matrix.
       P      Take the columnwise product.
            For coprimes, the column corresponding to each index will contain the
            index itself (GCD with itself) and several 1's (GCD with other indices),
            so the product is equal to the index.


6

Pyth、9バイト

{Ism{PhxG

テストスイート

説明:
{Ism{PhxG   | Full code
{Ism{PhxGdQ | With implicit variables filled
------------+------------------------------------------
   m      Q | For each char d in the input:
    {P      |  list the unique prime factors of
      hx d  |  the 1-based index of d in
        G   |  the lowercase alphabet
  s         | Group all prime factors into one list
{I          | Output whether the list has no duplicates

ピスはゼリーをアウトゴルフしたのですか?


6

パイソン2 - 122の 118バイト

@JonathanAllanのおかげで-4バイト

これは正直なところひどいですが、私はこれを投稿しないように長い間費やしました。

from fractions import*
def f(n):r=reduce;n=[ord(i)-96for i in n];return r(lambda x,y:x*y/gcd(x,y),n)==r(int.__mul__,n)

オンラインで試す


4
96 for〜> 96for; lambda x,y:x*y〜> int.__mul__
ジョナサンフレッチ

5

05AB1E、11バイト

Ç96-2.Æ€¿PΘ

オンラインでお試しください!

説明

Ç96-         # convert to character codes and subtract 96
    2.Æ      # get all combinations of size 2
       €¿    # gcd of each pair
         P   # product of gcds
          Θ  # is true

ファイナルはΘ本当に必要ですか?
Xcoder氏18

@ Mr.Xcoder:いいえ、そうではないと思います。2つの値を使用する必要があると思いましたが、今ではそれについての課題は何もないように見えます。Truthy / Falsyは大丈夫です。
エミグナ

@Emignaそのための明確化を追加しました。出力値のバリアントは2つだけであるべきです。
bodqhrohro

@bodqhrohro:OK。この新しい要件を満たすために、以前のバージョンにロールバックしました。
エミグナ

5

Brachylog、11バイト

ạ{-₉₆ḋd}ᵐc≠

オンラインでお試しください!

説明

ạ{-₉₆ḋd}ᵐc≠
ạ              Split the input into its character codes
 {     }ᵐ      For each one
  -₉₆          Subtract 96 (a -> 1, b -> 2 etc.)
     ḋd        And find the unique (d) prime factors (ḋ)
         c     Combine them into one list
          ≠    And assert they are all different

4

パイソン277の 68、64バイト

lambda a:all(sum(ord(v)%96%i<1for v in a)<2for i in range(2,26))

オンラインでお試しください!

基本的に、(入力のいくつかのペアは互いに素ではありません)場合にのみ(複数の入力を分割する数値i> 1があります)。


私たちのように見えるが持っていた同じ考えをしかし、あなたは数分で私を打つ:)缶は、あなたが使用することにより、これらの2つのバイトを保存しないall<2かかわら?
ビンセント


4

Perl 6の34の 32バイト

nwellnhofのおかげで-2バイト

{[lcm](@_)==[*] @_}o{.ords X-96}

オンラインでお試しください!

文字列を受け取り、TrueまたはFalseを返す匿名コードブロック。文字の最小公倍数が文字の積に等しい場合、それらは公約数を共有しません。

説明:

                     {.ords X-96}  # Convert the letters to a list of numbers
 {                 }o              # Pass result to the next codeblock
  [lcm](@_)           # The list reduced by the lcm
           ==         # Is equal to?
             [*] @_   # The list reduced by multiplication

間違っていない場合、これは機能しますか?(21バイト)
コナーオブライエン

ConorO'Brienません@、あなただけのマップされてきたa0大爆笑
ジョー・キング

@JoKingああ、大丈夫lol
コナーオブライエン

その戦略はバグが多かった、テストケース:dayでした。
Ørjanヨハンセン


3

J、36バイト

[:(1 =[:*/-.@=@i.@##&,+./~)_96+a.&i.

非ゴルフ

[: (1 = [: */ -.@=@i.@# #&, +./~) _96 + a.&i.

説明

[: (                            ) _96 + a.&i.  NB. apply fn in parens to result of right
                                  _96 + a.&i.  NB. index within J's ascii alphabet, minus 96.
                                               NB. gives index within english alphabet
   (1 =                         )              NB. does 1 equal...
   (    [: */                   )              NB. the product of...
   (                    #&,     )              NB. Flatten the left and right args, and then copy
   (                        +./~)              NB. right arg = a table of cross product GCDs
   (          -.@=@i.@#         )              NB. the complement of the identity matrix.
                                               NB. this removes the diagonal.

オンラインでお試しください!


[:(1=[:*/+./~#&,~#\~:/#\)_96+a.&i.以下のための34のバイト あなたが`1 =」のスペースを持っていた:)
ガレン・イワノフ

1
ありがとう@GalenIvanov
ジョナ


3

ゼリー、11バイト

ŒcO_96g/€ỊẠ

オンラインでお試しください!

  • ブール値に注意してくれたデニスに感謝

ŒcO_96g/€ỊẠ
Œc           All pairs of characters without replacement
  O          Code point of each character
   _96       Subtract 96. a->1, b->2, etc.
        €    For each pair:
      g/       Get the greatest common denominator
         Ị   abs(z)<=1? If they are all 1 then this will give a list of 1s
          Ạ  "All". Gives 1 if they are coprime, 0 if not.

2
ỊẠブール値を反転します。
デニス

3

MATL、10バイト

96-YF&fdA&

それ以外の場合の1coprimeの出力0

オンラインでお試しください!または、すべてのテストケースを確認します

説明

'man'たとえば、入力を検討してください。

96-  % Implicit input: string. Subtract 96 from (the codepoint of) each element
     % STACK: [13 1 14] 
YF   % Exponents of prime factoriation. Each number produces a row in the result
     % STACK: [0 0 0 0 0 1;
               0 0 0 0 0 0;
               1 0 0 1 0 0]
&f   % Two-output find: pushes row and column indices of nonzeros
     % STACK: [3; 3; 1], [1; 4; 6]
d    % Consecutive differences
     % STACK: [3; 3; 1], [3; 2]
A    % All: gives true if the array doesn't contain zeros
     % STACK: [3; 3; 1], 1
&    % Alternative in/out specification: the next function, which is implicit
     % display, will only take 1 input. So only the top of the stack is shown

3

eMainにより解釈されるマルコフアルゴリズム(474 484 463バイト、76 78 76ルール)

a->
d->b
f->bc
h->b
i->c
j->be
l->bc
n->bg
o->ce
p->b
q->q
r->bc
t->be
u->cg
v->bk
x->bc
y->e
z->bm
cb->bc
eb->be
gb->bg
kb->bk
mb->bm
qb->bq
sb->bs
wb->bw
ec->ce
gc->cg
kc->ck
mc->cm
qc->cq
sc->cs
wc->cw
ge->eg
ke->ek
me->em
qe->eq
se->es
we->ew
kg->gk
mg->gm
qg->gq
sg->gs
wg->gw
mk->km
qk->kq
sk->ks
wk->kw
qm->mq
sm->ms
wm->mw
sq->qs
wq->qw
ws->sw
bb->F
cc->F
ee->F
gg->F
kk->F
mm->F
qq->F
ss->F
ww->F
b->
c->
e->
g->
k->
m->
q->
s->
w->
FF->F
TF->F
!->.
->!T

最初の17のルールは、「複合文字」を「プライム文字」要素に織り込み、多重度を無視します。(たとえば、2のべき乗と5のべき乗の積として20の要因tがあるbeためになります。)

次の36個のルール(などcb->bc)は、結果の素因数をソートします。

次の9つの規則(などbb->F)は、繰り返される素因数をに置き換えF、さらに9つの規則(などb->)が残りの単一文字を取り除きます。

この時点で、空の文字列、または1つ以上Fのsの文字列があり、最後のルール->!T!T先頭にa を追加します。そして、ルールFF->FTF->Fのいずれかに結果を簡素化します!T!F。この時点で、!->.ルールを適用して、削除して!停止するように指示します。つまりT、互いに素な単語をF返すなどです。

(このコードが入力時に空の文字列を与える原因となった以前のバージョンのバグを指摘してくれたbodqhrohroに感謝しますa。)


1
どちらも与えTFaテストケース。
bodqhrohro

@bodqhrohroキャッチしてくれてありがとう!(結局、すべての改行を2バイトとしてカウントしていることに気付いたため、バイトカウントが減少しました。)
Misha Lavrov


2

Retina 0.8.2、45バイト


;
{`\w
#$&
}T`l`_l
M`;(##+)\1*;(#*;)*\1+;
^0

オンラインでお試しください!説明:


;

各文字の間、および先頭と末尾に区切り文字を挿入します。

{`\w
#$&

#各文字の先頭にa を付けます。

}T`l`_l

各文字1をアルファベットに戻し、asを削除します。次に、すべての文字が削除されるまで上記の操作を繰り返します。これにより、各文字が単項式の1から始まるアルファベットインデックスに変換されます。

M`;(##+)\1*;(#*;)*\1+;

2つの値が1より大きい共通因子を共有しているかどうかをテストします(これにより、単語などで共通因子を持つ複数の文字のペアを見つけることができますyearling)。

^0

一般的な要因が見つからなかったことを確認してください。


2

R + pracmaライブラリ、75バイト

function(w){s=utf8ToInt(w)-96;all(apply(outer(s,s,pracma::gcd),1,prod)==s)}

私は、Rにそのための組み込みがないという知識に関してgcdpracmaライブラリの関数を使用しています。私は、gcdの積を数値自体と比較するアプローチを使用しています。

65バイト(クレジット:@ J.Doe)

function(w)prod(outer(s<-utf8ToInt(w)-96,s,pracma::gcd))==prod(s)


1

Japt、14バイト

;à2 e_®nR+CÃrj

オンラインでお試しください!

入力を文字の配列として受け取ります。

使い方

;à2 e_m_nR+C} rj
;                 Use alternative predefined variables (in this case, C = "a-z")
 à2               Get all pairs
    e_            Does all pairs satisfy that...
      m_            when the character pair is mapped over...
        nR+C}         conversion from "a-z" to [1..26]
              rj    then the two numbers are coprime?


1

Java 10、86バイト

a->{var r=1>0;for(int i=1,s=0;++i<24;r&=s<2,s=0)for(var c:a)s+=c%96%i<1?1:0;return r;}

@VincentのPython 3回答のポート。

オンラインでお試しください。

説明:

a->{                 // Method with character-array parameter and boolean return-type
  var r=1>0;         //  Result-boolean, starting at true
  for(int s=0,       //  Sum integer, starting at 0
      i=1;++i<24     //  Loop `i` in the range (1, 24)
      ;              //    After every iteration:
       r&=s<2,       //     If the sum is >= 2: change the result to false
       s=0)          //     And reset the sum to 0
     for(var c:a)    //   Inner loop over the input-characters
       s+=c%96%i<1?  //    If the current character modulo-96 is divisible by `i`
           1         //     Increase the sum by 1
          :          //    Else
           0;        //     Leave the sum the same
  return r;}         //  Return the result-boolean


0

q、121 111バイト

{$[1=count x;1b;1b=distinct{r:{l:{$[0~y;:x;.z.s[y;x mod y]]}[y;]'[x];2>count l where l<>1}[x;]'[x]}[1+.Q.a?x]]}


0

スタックス、16 バイト

è'B╕i4à!ùà╫æor4Z

実行してデバッグする

説明

2S{M{$e96-mm{E:!m|A     #Full program, unpacked, implicit input
2S                      #Generate all combinations of size 2
  {       m             #Map for each element
   M                    #Split into size of 1 element
    {       m           #Map for each element
     $e                 #Convert to number
       96-              #Subtract 96
           {    m       #Map for each element
            E:!         #Explode array onto stack, are they coprime
                 |A     #Are all elements of array truthy

Trueの場合は1、Falseの場合は0を出力します。

おそらく、数値部分への変換を行うためのより良い方法がありますが、機能します。


スタックスの著者はこちら。staxをお試しいただきありがとうございます!以下は、10バイトに圧縮するアルゴリズムを使用したプログラムです。 2SOF{96-F:!* あなたがそれについてもっと知りたいなら、私に知らせてください。最初のものは無料です!
再帰的

@再帰Staxを作成していただきありがとうございます!現時点では、私の選択したゴルフ言語です。私はあなたの答えがどのように機能するかを見ることができます。今後も私の答えを改善するために働き続けなければなりません。
マルチ

0

APL(NARS)、16文字、32バイト

{(×/p)=∧/p←⎕a⍳⍵}

この他の使用方法では、LCM()=×/を使用しました。高速ですが、入力配列が十分に長い場合はオーバーフローします。他の代替ソリューションは少し遅くなります:

{1=×/y∨y÷⍨×/y←⎕a⍳⍵} 
{1=≢,⍵:1⋄1=×/{(2⌷⍵)∨1⌷⍵}¨{x←97-⍨⎕AV⍳⍵⋄(,x∘.,x)∼⍦x,¨x}⍵}

これは以下の関数よりも10倍速い(または+)

∇r←h m;i;j;k;v
   r←i←1⋄k←≢v←97-⍨⎕AV⍳m
A: →F×⍳i>k⋄j←i+1⋄→C
B:   →E×⍳1≠(j⌷v)∨i⌷v⋄j←j+1
C:   →B×⍳j≤k
D: i←i+1⋄→A
E: r←0
F:
∇

私はこれがより簡単で、速く、信頼できるため(オーバーフローの可能性が少ないため)、書くのが簡単で、それがどうあるべきか(それがさらにバイト数があっても...)

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.