Apakah ini n-berbicara?


33

Terinspirasi oleh Apakah berbicara dua kali lipat? Saya menemukan tantangan yang lebih sulit. Diberikan string, tentukan apakah string tersebut adalah n-spoke , untuk setiap n2 .

Bicara didefinisikan dengan mengulangi setiap huruf n kali. Dengan n=4 , string Helloditransformasikan menjadi HHHHeeeelllllllloooo. Tujuan Anda adalah untuk mengetahui apakah input tersebut merupakan output yang valid untuk setiap transformasi n-spoke.

Perlu dicatat bahwa kalimat apa pun yang valid untuk berbicara n=2k , untuk n = 2 k , juga berlaku untuk berbicara k. Dengan demikian, bagian yang sulit untuk dipecahkan adalah nilai ganjil dari n .

Memasukkan

Sebuah string yang terdiri dari setidaknya 2 karakter. Input juga bisa berupa daftar karakter. Input peka huruf besar-kecil.

Keluaran

Truthyjika stringnya adalah n-speak, falseysebaliknya.

Contohnya

Kasus yang benar

HHeelllloo,,  wwoorrlldd!!
TTTrrriiipppllleee   ssspppeeeaaakkk
QQQQuuuuaaaaddddrrrruuuupppplllleeee    ssssppppeeeeaaaakkkk
7777777-------ssssssspppppppeeeeeeeaaaaaaakkkkkkk
999999999
aaaabb
aaaaaaaabbbbcc
aaaaabbbbb
@@@

Jika Anda ingin membuat kasus kebenaran tambahan, Anda dapat menggunakan skrip MathGolf ini . Tempatkan string dalam tanda kutip, dan nilai n sebagai input.

Kasus palsu

Hello, world!
TTTrrriiipppllleee   speak
aaaaaaaaaaaaaaaab
Ddoouubbllee  ssppeeaakk
aabbab
aaaabbb
a (does not need to be handled)
(empty string, does not need to be handled)

Tentu saja, karena ini adalah kode golf, bersiaplah untuk memotong beberapa byte!


aabbab
Kasing

Kasing uji yang disarankan:aaaabbb
640KB

Saya akan menambahkan keduanya besok, saran bagus.
Maks

4
Saya benar-benar merasa tersanjung dan tersanjung bahwa Anda telah menggunakan dan memperluas tantangan saya :)
AJFaraday

@AJFaraday senang Anda menyukainya! Saya menikmati kedua tantangan Anda, yang memberi saya ide untuk yang satu ini. Mungkin akan ada tantangan yang lebih sulit segera hadir.
Maks

Jawaban:


16

APL (Dyalog Unicode) , 12 byte

Dijalankan dengan ⎕io←0

1≠∨/⍸2≠/∊00

Cobalah online!

Bermain golf bersama Adám .

Pada input (contoh :, "aaccccaaaaaabb"gunakan ""untuk menunjukkan string (array karakter) dan ''untuk menunjukkan char)

∊0⍞0 mengelilingi dengan 0s dan ratakan, 0 'a' 'a' 'c' 'c' 'c' 'c' 'a' 'a' 'a' 'a' 'a' 'a' 'b' 'b' 0

2≠/ melakukan berpasangan tidak sama, 1 0 1 0 0 0 1 0 0 0 0 0 1 0 1

dapatkan indeks-indeks 0, 0 2 6 12 14

∨/ menghitung GCD, 2

1≠ Apakah ini tidak sama dengan 1?


10

Java 10, 85 byte

s->{var r=0>1;for(int i=0;++i<s.length();)r|=s.matches("((.)\\2{"+i+"})*");return r;}

Regex porting dari jawaban JavaScript @Arnauld .

Cobalah online.

Penjelasan:

s->{                          // Method with String parameter and boolean return-type
  var r=0>1;                  //  Result-boolean, starting at false
  for(int i=0;++i<s.length();)//  Loop `i` in the range [1, input-length):
    r|=                       //   Change the result to true if:
      s.matches("((.)\\2{"+i+"})*");
                              //    The input-String matches this regex
                              // NOTE: String#matches implicitly adds a leading ^ and 
                              //       trailing $ to match the full String
  return r;}                  // After the loop, return the result-boolean

Penjelasan regex:

^((.)\2{i})*$                 // Full regex to match, where `i` is the loop-integer
^           $                 // If the full String matches:
  (.)                         //  A character
     \2{i}                    //  Appended with that same character `i` amount of times
 (        )*                  //  And that repeated zero or more times for the entire string


7

JavaScript (ES6), 53 byte

Berasal dari ekspresi reguler yang digunakan oleh @wastl di Apakah ini berbicara ganda? .

s=>[...s].some((_,n)=>s.match(`^((.)\\2{${++n}})*$`))

Cobalah online!


Versi rekursif, 55 byte

s=>(g=n=>s[++n]&&!!s.match(`^((.)\\2{${n}})*$`)|g(n))``

Cobalah online!

Berkomentar

s => (                    // s = input string
  g = n =>                // g is a recursive function taking a repetition length n
    s[++n] &&             // increment n; abort if s[n] is not defined
    !!s.match(            // otherwise, test whether s consists of groups of:
      `^((.)\\2{${n}})*$` //   some character, followed by n copies of the same character
    )                     //
    | g(n)                // or whether it works for some greater n
)``                       // initial call to g with n = [''] (zero-ish)


6

Python 2, 73 70 69 67 bytes

lambda s:s in[''.join(c*n for c in s[::n])for n in range(2,len(s))]

Try it online!

-4 bytes, thanks to Jitse


2
You can save 3 bytes by replacing set(...) with {...}
Jitse

1
Also, you can remove the space in ...1 in[...
Jitse

@Jitse Thanks :)
TFeld


5

QuadS, 16 bytesSBCS

1≠∨/⍵
(.)\1*
⊃⍵L

Try it online!

1≠ is 1 different from

∨/ the GCD

 of the result of

(.)\1* PCRE Searching for any character followed by 0 or more repetitions thereof

⊃⍵L and returning the first of the match lengths (i.e. the length of the match)



4

T-SQL 2008 query, 193 bytes

DECLARE @ varchar(max)='bbbbbbccc';

WITH C as(SELECT number+2n,@ t
FROM spt_values
WHERE'P'=type
UNION ALL 
SELECT n,stuff(t,1,n,'')FROM C
WHERE left(t,n)collate Thai_Bin=replicate(left(t,1),n))SELECT 1+1/~count(*)FROM C
WHERE''=t

Try it online


Is "collate Thai_Bin" really necessary?
Dr Y Wit

1
@DrYWit it depends, the database could be set up as case sensitive. But case sensitive databases are not a popular choice. This could be handled better differently using HASHBYTES or maybe VARBINARY, but that is more costly in bytes
t-clausen.dk

4

PHP, 76 75 bytes

while(($x=strspn($argn,$argn[$n+=$x],$n))>1&&($m=max($m,$x))%$x<1);echo!$x;

Try it online!

First attempt, a somewhat naïve iterative approach.

Ungolfed:

// get the length of the next span of the same char
while( $s = strspn( $argn, $argn[ $n ], $n ) ) {

    // if span is less than 2 chars long, input is not n-speak
    if ( $s < 2 ) {
        break;
    }

    // k is GCD
    $k = max( $k, $s );

    // if span length does not divide evenly into GCD, input is not n-speak
    if( ( $k % $s ) != 0 ) {
        break;
    }

    // increment current input string index
    $n += $s;

}

-1 byte, thx to @Night2!


4

Perl 6, 30 27 26 bytes

{1-[gcd] m:g/(.)$0*/>>.to}

Try it online!

Also uses the GCD trick, but uses the index of the end position of each run matched by the regex. Returns a negative number (truthy) if n-speak, zero (falsey) otherwise.




3

Brachylog, 5 bytes

ġz₂=Ṁ

Try it online!

Takes input through the input variable and outputs through success or failure.

At first I thought this would actually be shorter than my solution to Is it double speak?, but then I realized that ġ can and will try a group length of 1.

ġ        It is possible to split the input into chunks of similar length
 z₂      such that they have strictly equal length, and zipped together
    Ṁ    there are multiple results
   =     which are all equal.

3

Japt , 8 bytes

ò¦ mÊrÕÉ

Try it

ò¦ mÊrÕÉ     :Implicit input of string
ò            :Partition by
 ¦           :  Inequality
   m         :Map
    Ê        :  Length
     r       :Reduce by
      Õ      :  GCD
       É     :Subtract 1
             :Implicit output of boolean negation

3

Kotlin, 78 bytes

{s->(2..s.length/2).any{i->s.chunked(i).all{z->z.length==i&&z.all{z[0]==it}}}}

Try it online!

Explanation

{s->                      Take a string as input
  (2..s.length/2)         The each string needs two parts at least, prevents the case "aaa" is 3-speak
    .any{i->              If there is any n (in this case i) that is n-speak return true
      s.chunked(i)        Split into length i substrings
      .all{z->            All substrings z
        z.length==i       Should be completely full, ie. "aaa"->["aa","a"]
        &&                And
        z.all{            All chars (it)
          z[0]==it        Should be the same as the first char
        }
      }
    }
  }

Perhaps the description is unclear, but "aaa" is valid 3-speak. The input string should have at least two characters, but they do not need to be different.
maxb

@maxb, ok cool. That should be -2 bytes. Thanks for the update. I'll fix that tomorrow
Brojowski

3

Scala, 80 bytes

s=>"(.)\\1*".r.findAllIn(s).map(_.size).reduce((x,y)=>(BigInt(x) gcd y).toInt)>1

Try it online!

PS. Original solution was based on split function but it's longer (83 bytes).

s=>(s+s).split("(.)(?!\\1)").map(_.size+1).reduce((x,y)=>(BigInt(x) gcd y).toInt)>1

This returns true for input aab, unfortunately.
maxb

@maxb, thanks for checking. s. replaced with (s+s). to handle that.
Dr Y Wit

Good job! Though now I noticed that it fails for aaaabb and aabbbb.
maxb

@maxb, apologies, now I tested on all your test cases from starting post.
Dr Y Wit



2

Brain-Flak, 96 bytes

{<>({}())<>({}[({})]){{}<>({}<>){{(({})){({}[()])<>}{}}<>([{}()]({}<>)<>)}(<>)<>}{}}<>{}({}[()])

Try it online!

Uses the same GCD trick that many other submissions use. Output is 0 if the input is not n-speak, and a positive integer otherwise.

# For each character in the input
{

  # Add 1 to current run length
  <>({}())<>

  # If current and next characters differ:
  ({}[({})]){

    # Clean up unneeded difference
    {}<>

    # Move current run length to left stack, exposing current GCD on right stack
    ({}<>)

    # GCD routine: repeat until L=0
    {

      # Compute L mod R
      {(({})){({}[()])<>}{}}<>

      # Move R to left stack; finish computing L mod R and push to right stack
      ([{}()]({}<>)<>)

    }

    # Push 0 for new run length
    (<>)<>

  }{}

}

# Output GCD-1
<>{}({}[()])

2

Oracle SQL, 182 bytes

select+1-sign(min(length(x)-(select sum(length(regexp_substr(x,'(.)\1{'||i||'}',1,level)))from t connect by level<length(x))))from(select x,level i from t connect by level<length(x))

It works with an assumption that input data is stored in a table t(x), e.g.

with t(x) as (select 'HHeelllloo,,  wwoorrlldd!!' from dual)

2

K (ngn/k), 29 23 bytes

{~|/(&/s@&1<s)!s:#'=:x}

Try it online!

edit: removed some unnecessary colons (i know when a monadic is required but it's not always clear to me if there's ambiguity so i default to including the colon) and changed the mod x-y*x%y to ngn/k's y!x, which meant i could remove a variable assignment


1

APL (Dyalog Unicode), 24 22 bytesSBCS

Anonymous tacit prefix function.

⊂∊1↓⍳∘≢{⍵/⍨(≢⍵)⍴⍺↑⍺}¨⊂

Try it online!

 enclose the string to treat map using the entire string
 e.g. "aaabbb"

⍳∘≢{ for each of the ɩndices 1 through the tally of characters in the string:
 e.g. 3

⍺↑⍺ take the current number of elements from the current number, padding with 0s
 e.g. [3,0,0]

(≢⍵)⍴ cyclically reshape into the shape of the tally of characters in the string
  e.g. [3,0,0,3,0,0]

⍵/⍨ use that to replicate the string's characters
  "aaabbb"

1↓ drop the first one (n = 1)

⊂∊ is the the entire string a member of that list?


Are you dividing the input string into n-sized chunks, and checking that all characters are equal within each chunk? I haven't gotten into APL, but it's definitely the most readable "golfing" language.
maxb

@maxb I'm in the process of writing an explanation. I'm filtering with all possible masks [1,0,0,1,0,0…] etc. I'll be happy to teach you APL (it doesn't take long to learn). Just pop unto the APL Orchard.
Adám


@Cowsquack Clever, and different, so why don't you post {1<∨/≢¨⍵⊆⍨≢¨∪\⍵}?
Adám

Unfortunately it fails for aacccaaaaabb
Kritixi Lithos

1

Retina 0.8.2, 28 bytes

M!`(.)\1*
.
.
^(..+)(\1|¶)*$

Try it online! Link includes test cases. Explanation:

M!`(.)\1*

Split the text into runs of identical characters.

.
.

Replace them all with the same character.

^(..+)(\1|¶)*$

Check whether the GCD of the lengths of the runs is greater than 1.



1

MathGolf, 14 bytes

£─╞möl╠mÅ▀£╙╓┴

Try it online!

Explanation

Checks all possible divisions of the input string into equal length chunks, and checks if there is a partition in which all chunks have just one unique character.

£                length of string with pop
 ─               get divisors
  ╞              discard from left of string/array (removes 1)
   mö            explicit map using 7 operators
     l           push input
      ╠          divide input into chunks of size k
       mÅ        explicit map using 2 operators
         ߜ      number of unique elements of list
           ╙     get maximum number of unique characters per chunk
                 loop ends here
            ╓    get the minimum of all maximums
             ┴   check if equal to 1


1

Pyth, 8 bytes

<1iFhMr8

Try it online!

<1iFhMr8Q   Implicit: Q=eval(input())
            Trailing Q inferred
      r8Q   Run length encode Q into [count, character]
    hM      Take first element of each
  iF        Reduce by GCD
<1          Is 1 less than the above? Implicit print

1

Perl 5 -n, 38 bytes

for$i(1..y///c){print/^((.)\2{$i})*$/}

Try it online!

The print"\n" in the footer is needed to separate the outputs.

Straightforward loop through all possible ns. Outputs nothing for "1-speak", anything else for n-speak where n > 1.

Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.