Cordas divisíveis

Sep 09 2020

Tarefa

Dada uma string s, produza um valor verdadeiro se o código ASCII de cada letra for divisível pelo comprimento de s, e um falsey caso contrário.

Entrada / Saída

A entrada é uma string não vazia que contém apenas ASCII [32-126]. A saída é um valor verdadeiro / falsey padrão. Observe que você pode mudar os valores, por exemplo, retornando 0/ Falsese divisível e vice-versa

Casos de teste

Input         Output

Hello         False       (72 101 108 108 111), 5
lol           True        (108 111 108), 3
Codegolf      False       (67 111 100 101 103 111 108 102), 8
A             True        (65), 1
nope          False       (110 111 112 101),4
8  8          True        (56 32 32 56), 4

Respostas

3 LuisMendo Sep 09 2020 at 15:18

MATL , 4 bytes

tn\~
  • Para strings divisíveis, a saída é um vetor contendo apenas 1s, o que é verdade .
  • Caso contrário, a saída é um vetor contendo vários se 1pelo menos um 0, o que é falso .

Experimente online! Ou verifique todos os casos de teste, incluindo teste de veracidade / falsidade.

Como funciona

t   % Implicit input. Duplicate
n   % Number of elements
\   % Modulo
~   % Negate. Implicit display
8 ovs Sep 09 2020 at 15:57

Befunge-98 (FBBI) , 31 bytes

A saída é via código de saída 1, 0para verdade , para casos falsey.

#v~\1+
v>53p
>:#v_1q
^  >' %#@_

Experimente online!


Código em execução com entradas lole ab:

pequenos números representam valores de byte literais

8 rak1507 Sep 09 2020 at 17:20

Haskell , 42 39 bytes

(<1).sum.(map=<<flip(mod.fromEnum).length)
f s=sum[fromEnum c`mod`length s|c<-s]<1

3 bytes a menos graças a ovs e xnor!

Experimente online!

7 ovs Sep 09 2020 at 15:06

05AB1E , 5 bytes

ÇsgÖP

Experimente online!

Comentou

        # implicit input    "lol"
Ç       # push ASCII value  [108, 111, 108]
 s      # swap (with input) [108, 111, 108], "lol"
  g     # length            [108, 111, 108], 3
   Ö    # is divisible?     [1, 1, 1]
    P   # product           1
5 Shaggy Sep 10 2020 at 16:17

Rockstar , 205 192 175 162 bytes

Bem, isso foi divertido. A Rockstar não tem como ler o comprimento de uma string diretamente, não pode converter caracteres em pontos de código e não tem operador de módulo. Surpreso, deu certo neste curto!

listen to S
cut S
X's0
D's0
while S at X
N's32
while N-127
cast N into C
if C is S at X
let M be N/S
turn down M
let D be+N-S*M

let N be+1

let X be+1

say not D

Experimente aqui (o código terá de ser colado)

4 Mukundan314 Sep 09 2020 at 17:35

Pyth , 8 bytes

!sm%CdlQ

Experimente online!

!sm%CdlQ
  m       : map implicit input on
          : lambda d:
    Cd    :   Ascii value of d
   %  lQ  :   mod length of input
 s        : sum result of map
!         : logical negate it
3 Shaggy Sep 09 2020 at 15:57

JavaScript, 32 bytes

Ouput é revertido.

s=>Buffer(s).some(c=>c%s.length)

Experimente online!

3 Kaddath Sep 10 2020 at 21:30

PHP , 56 52 bytes

for(;$c=ord($argn[$i++]);$c%strlen($argn)?die(f):1);

Experimente online!

A saída é revertida

A execução pára com fse qualquer caractere não for divisível, ou string vazia (falso em PHP) se todos forem divisíveis

EDIT: salvou 4 bytes graças a @ 640 KB

2 Dion Sep 09 2020 at 15:06

Python 2 , 41 39 bytes

lambda s:all(ord(i)%len(s)<1for i in s)

Experimente online!

-2 bytes graças a @ovs

2 GalenIvanov Sep 09 2020 at 15:34

K (ok) , 11 bytes

{~+/(#x)!x}

Experimente online!

2 madlaina Sep 09 2020 at 16:48

Ferrugem , 36 bytes

|s|s.iter().all(|x|1>x%s.len()as u8)

Experimente online!

Recebe a entrada como um &[u8], gera a bool.

2 Razetime Sep 09 2020 at 17:13

Pip , 12 bytes

!$+(A_Ma)%#a

Experimente online!

Explicação

!$+(A_Ma)%#a a → input
   (A_Ma)    Map a to Unicode/ASCII codepoints
         %#a Modulo the list by it's length
 $+          Sum up the remainders
!            Not(returns 0 for any positive number, 1 for 0)
2 Razetime Sep 09 2020 at 17:39

Ruby , 43 37 36 32 bytes

->a{a.bytes.all?{|n|n%a.size<1}}

se apenas o mapa pudesse ser usado em strings ..

-10 bytes de ovs.

-1 byte de Dingus.

Experimente online!

2 NahuelFouilleul Sep 09 2020 at 21:05

Perl 5 -pF , 20 bytes

$_=!grep ord()%@F,@F

Experimente online!

2 Noodle9 Sep 09 2020 at 16:36

C (gcc) , 54 53 bytes

l;r;f(char*s){l=strlen(s);for(r=0;*s;)r|=*s++%l;l=r;}

Experimente online!

Retorna falsey se o valor ASCII de cada caractere for divisível pelo comprimento da string de entrada ou verdadeiro caso contrário.

Explicação:

l;r;f(char*s){l=strlen(s);for(r=0;*s;)r|=*s++%l;l=!r;}  
l;r;                                                  // Declare 2 int variables
    f(                                                // Function f taking
      char*s){                                        //   string parameter s  
              l=strlen(s);                            // Store length of s in l
                          for(                        // Loop
                              r=0;                    //   initialising r to 0
                                  *s;)                //   until end of s  
                                      r|=             // Bitwise or r with 
                                         *s           //   the ASCII value of the next
                                                      //   character...  
                                           ++         // Aside: push s pointer forward
                                             %l;      //  ... mod the string length
                                                r=l;  // Return r (r will be 0
                                                      //   iff every character was
                                                      //   divisible by l)
2 J42161217 Sep 09 2020 at 15:11

Linguagem Wolfram (Mathematica) , 40 bytes

{0}==##&@@ToCharacterCode@#~Mod~Tr[1^#]&

Experimente online!

obrigado a @att por salvar alguns bytes

1 Adám Sep 09 2020 at 15:24

APL (Dyalog Extended) , 7 bytes ( SBCS )

Função de prefixo tácito anônima

⍱≢|⎕UCS

Experimente online!

 alguma das seguintes não é verdadeira (diferente de zero)?

 O comprimento

| divide (lit. divisão restante ao dividir)

⎕UCS os pontos de código

1 LiefdeWen Sep 09 2020 at 15:56

C # (.NET Core) , 25 bytes

a=>a.All(x=>x%a.Length<1)

Experimente online!

1 Shaggy Sep 09 2020 at 16:36

Japt -e , 6 bytes

c vNÎÊ

Tente

1 KevinCruijssen Sep 09 2020 at 16:42

MathGolf , 4 bytes

$h÷╓

Insira como uma lista de personagens.

Experimente online.

Explicação:

$     # Get the codepoint of each character in the (implicit) input-list
 h    # Push the length of this list (without popping the list itself)
  ÷   # Check for each codepoint if it's divisible by this length
   ╓  # Pop and push the minimum of the list
      # (after which the entire stack joined together is output implicitly as result)
1 ovs Sep 09 2020 at 15:18

Gelatina , 4 bytes

LḍOP

Experimente online! ou Verifique todos os casos!

Comentado: (pelo menos acho que funciona assim)

   P  # product of ...
L     #   does the length 
 ḍ    #   ... divide ...
  O   #   the char codes
1 DominicvanEssen Sep 09 2020 at 16:20

R , 39 38 bytes

Editar: -1byte graças à nova regra de que podemos produzir TRUE para FALSE e FALSE para TRUE

function(s)any(utf8ToInt(s)%%nchar(s))

Experimente online!

Ou tente a versão original de 39 bytes que produz TRUE para TRUE ...

1 Stuart Sep 11 2020 at 16:10

Clojure, 41 chars

(every? #(= 0 (mod (int %) (count x))) x)

Removendo espaços após o comentário 37 caracteres

(every? #(= 0(mod(int %)(count x)))x) 
1 Dion Sep 10 2020 at 20:07

MAWP , 34 33 24 23 bytes

`|_=M0=A0/[M%{0:.}?`]1:

Tente!

Obrigado a @Razetime por economizar 9 bytes!

Explicação:

`        Remove starting 1 on stack
|        Push input on stack as ASCII codes
_=M      Set variable M to length of stack (length of input)
0=A      Set variable A to 0
0/       Push 0 and cycle stack
[        Start of loop
M%       Modulo by M
{0:.}    If not 0 then print 0 and terminate
?`       If 0 then pop value
]        End of loop
1:       Print 1
1 xash Sep 12 2020 at 15:48

Brachylog , 8 bytes

ạfᵐ∋ᵛ~l?

Experimente online!

ạfᵐ∋ᵛ~l?
ạ        characters to integer
 fᵐ      find all factors
   ∋ᵛ    every list of factors contain …
     ~l? the length of the input

Versão alternativa,

⟨ạzl⟩%ᵛ0
⟨fhg⟩    forks! fA & gB ∧ [A, B]h
 ạzl     zip the code blocks with the length;
          [[108, 3], [111, 3], [108, 3]]
     %ᵛ0 every list must be 0 after modulo
1 Steve28 Sep 13 2020 at 08:06

Python 3 , 55 52 bytes

N=input();print(not sum([ord(i)%len(N) for i in N]))

Experimente online!

1 2014MELO03 Sep 17 2020 at 03:26

GolfScript , 20 bytes

.,0@{(3$%@+\}3$*;!\;

Experimente online!

Isso gera 1 se a string for divisível e 0 se não for. Seja S a corda e L seu comprimento.

.,0@                  # The stack from bottom up will be: L  0  S
    {       }3$* # Execute this block L times ( # Separate first char from the string as a number 3$%             # Previous number mod L
         @+\          # Add result to the acumulator
                ;     # Discard the ""
                 !    # 1 iff the acumulator is 0
                  \;  # Discard L
Neil Sep 09 2020 at 16:06

Carvão , 8 bytes

¬⊙θ﹪℅ιLθ

Experimente online! O link é para a versão detalhada do código. A saída é um booleano Charcoal, ou seja, -para verdadeiro, nada para falso. Explicação:

  θ         Input string
 ⊙          Is there a character where
     ι      Current character
    ℅       Ordinal
   ﹪        Modulo (i.e. is not divisible by)
       θ    Input string
      L     Length
¬           Boolean NOT
            Implicitly print

⬤θ¬﹪℅ιLθ também funciona, é claro.

GalenIvanov Sep 09 2020 at 16:06

Fator , 62 bytes

: f ( s -- ? ) dup length [ mod ] curry [ + ] map-reduce 0 = ;

Experimente online!

BlackPanther Sep 09 2020 at 18:08

C # (compilador interativo do Visual C #) , 81 bytes

(s)=>{var bs = ASCIIEncoding.ASCII.GetBytes(s);return bs.All(b=>b%s.Length==0);};

Experimente online!

C # (compilador interativo do Visual C #) , 27 26 bytes

s=>s.All(c=>c%s.Length<1);

Experimente online!