Sheffle tho vawols ureund!


42

Dada uma cadeia de entrada, de saída que string com todas as vogais a, e, i, oe utrocou de forma aleatória entre si.

Por exemplo, na seqüência this is a test, há 4 vogais: [i, i, a, e]. Um embaralhamento válido dessas vogais poderia, [a, i, e, i]portanto, produzir a saída thas is e tist.

Sobre embaralhar

Todos os shuffles devem ser igualmente prováveis se considerarmos que vogais iguais são distintas . Para o exemplo acima, esses 24 shuffles são possíveis:

[i 1 , i 2 , a, e] [i 1 , i 2 , e, a] [i 1 , a, i 2 , e] [i 1 , a, e, i 2 ]
[i 1 , e, i 2 , a] [i 1 , e, a, i 2 ] [i 2 , i 1 , a, e] [i 2 , i 1 , e, a]
[i 2 , a, i 1 , e] [i 2 , a, e, i 1 ] [i 2 , e, i 1 , a] [i 2 , e, a, i 1 ]
[a, i 1 , i 2 , e] [a, i 1 , e, i 2 ] [a, i 2 , i 1 , e] [a, i 2 , e, i 1 ]
[a, e, i 1 , i 2 ] [a, e, i 2 , i 1 ] [e, i 1 , i 2 , a] [e, i 1 , a, i 2 ]
[e, i 2 , i 1 , a] [e, i 2 , a, i 1 ] [e, a, i 1 , i 2 ] [e, a, i 2 , i 1 ]

Cada um deve ser igualmente provável.

Você não pode tentar embaralhar aleatoriamente toda a cadeia até encontrar uma onde todas as vogais estejam no lugar certo. Em resumo, o tempo de execução do seu código deve ser constante se a entrada for constante.

Entradas e saídas

  • Você pode assumir que todas as letras da entrada serão minúsculas ou maiúsculas. Você também pode oferecer suporte a maiúsculas e minúsculas, embora isso não lhe dê nenhum bônus.

  • A entrada sempre consistirá em caracteres ASCII imprimíveis. Todos os caracteres que estão na entrada devem estar na saída, apenas as vogais devem ser embaralhadas e nada mais.

  • A entrada pode estar vazia. Não há garantia de que a entrada contenha pelo menos uma vogal ou pelo menos uma não vogal.

  • Você pode obter a entrada de STDIN, como um parâmetro de função, ou qualquer coisa semelhante.

  • Você pode imprimir a saída STDOUT, retorná-la de uma função ou algo semelhante.

Casos de teste

A primeira linha é a entrada fornecida. A segunda linha é uma das saídas possíveis.

<empty string>
<empty string>

a
a

cwm
cwm

the quick brown fox jumps over the lazy dog.
tho qeuck brewn fax jumps ovir the lozy dog.

abcdefghijklmnopqrstuvwxyz
abcdefghujklmnipqrstovwxyz

programming puzzles & code golf
pregromming pezzlos & coda gulf

fatalize
fitaleza

martin ender
mirten ander

Pontuação

Isso é , para que usuários logistas e bytes ganhem .


17
Você Inglês / povo americano e sua falta de ycomo vogal ..;)
Kevin Cruijssen

6
@KevinCruijssen Eu não sou um falante nativo e também consideraria yuma vogal, mas no último desafio em que eu disse que yera uma vogal, me perguntaram por que escolhi isso!
Fatalize 31/08/16

7
@KevinCruijssen, letras não são vogais: sons são.
31816 Peter Taylor

6
+1 para cwm. Mantendo o alpinismo e / ou o galês vivos;)
Decay Beta

2
@KevinCruijssen não tem um co w sobre vo w els que não são comumente considerados assim.
CorsiKa

Respostas:


13

Gelatina , 15 bytes

f€“¡ẎṢɱ»ðœpżFẊ¥

Experimente online!

Como funciona

f€“¡ẎṢɱ»ðœpżFẊ¥  Main link. Argument: s (string)

  “¡ẎṢɱ»         Yield "aeuoi"; concatenate "a" with the dictionary word "euoi".
f€               Filter each character in s by presence in "aeuoi".
                 This yields A, an array of singleton and empty strings.
        ð        Begin a new, dyadic chain. Left argument: A. Right argument: s
         œp      Partition s at truthy values (singleton strings of vowels) in A.
            FẊ¥  Flatten and shuffle A. This yields a permutation of the vowels.
           ż     Zip the partition of consonants with the shuffled vowels.

Por que isso parece bastante lento em comparação com outras respostas?
Fatalize 31/08/16

Jelly importa SymPy e NumPy antes de qualquer outra coisa. Este programa e o programa vazio têm aproximadamente o mesmo tempo de execução.
Dennis


5
@ Dennis Por curiosidade, por que Jelly construiu palavras no dicionário? De onde ele tira essas palavras do dicionário?
Kevin Cruijssen

1
@KevinCruijssen Quando eu projetei o Jelly, já havia algumas línguas de golfe que usavam shoco , e o simples uso de um dicionário de inglês parecia uma boa maneira de melhorar essa idéia. Usei o arquivo /usr/share/dict/wordsdo meu computador e o incluí no interpretador de geléia.
Dennis

17

R, 92 91

Ainda não posso comentar, por isso estou adicionando minha própria resposta, embora muito parecida com a resposta @ Andreï Kostyrka (acredite ou não, mas veio com ela de forma independente).

s=strsplit(readline(),"")[[1]];v=s%in%c("a","e","i","o","u");s[v]=sample(s[v]);cat(s,sep="")

Ungolfed

s=strsplit(readline(),"")[[1]]    # Read input and store as a vector
v=s%in%c("a","e","i","o","u")     # Return TRUE/FALSE vector if vowel
s[v]=sample(s[v])                 # Replace vector if TRUE with a random permutation of vowels
cat(s,sep="")                     # Print concatenated vector

Guardou um byte graças a @Vlo

s=strsplit(readline(),"")[[1]];s[v]=sample(s[v<-s%in%c("a","e","i","o","u")]);cat(s,sep="")

5
Honestamente, eu não posso acreditar. Só brincando. Bom truque para salvar alguns bytes!
Andreï Kostyrka 31/08/16

Para ser sincero, não estou roubando suas idéias para dar mais uma resposta à minha pergunta.
Andreï Kostyrka 31/08/16

3
Hehe, tenho que levá-los upvotes doces para que eu possa comentar;)
Billywob

Salve um byte com atribuição em linha 91 bytess=strsplit(readline(),"")[[1]];s[v]=sample(s[v<-s%in%c("a","e","i","o","u")]);cat(s,sep="")
Vlo 01/09/16

Salve outro byte usando em el()vez de [[1]].
Andreï Kostyrka 23/03

11

R, 99 98 89 bytes

x=el(strsplit(readline(),""))
z=grepl("[aeiou]",x)
x[z]=x[sample(which(z))]
cat(x,sep="")

Parece ser a primeira solução legível por humanos! Obrigado a Giuseppe por salvar 9 bytes!

Casos de teste:

tho qaeck bruwn fux jemps over tho lozy dig.
progremmang pozzlos & cide gulf

Parece que não há como fazer uma atribuição interna de variável (interna, como, cat) e, novamente, algumas pessoas vão provar que estou errado ...


2
letters[c(1,5,9,15,21)]é 1 byte mais longo, e OEIS A161536 e A215721 também parecem ter pouca ou nenhuma ajuda.
Andreï Kostyrka 31/08/16

Não z=grepl("[aeiou]",x)seria mais curto?
Giuseppe

@ Giuseppe Você fez isso de novo! Obrigado.
Andreï Kostyrka

10

CJam, 23 bytes

lee_{"aeiou"&},_mrerWf=

Experimente online!

Explicação

l            e# Read input, e.g. "foobar".
ee           e# Enumerate, e.g. [[0 'f] [1 'o] [2 'o] [3 'b] [4 'a] [5 'r]].
_            e# Duplicate.
{"aeiou"&},  e# Keep those which have a non-empty intersection with this string
             e# of vowels, i.e. those where the enumerated character is a vowel.
             e# E.g. [[1 'o] [2 'o] [4 'a]].
_            e# Duplicate.
mr           e# Shuffle the copy. E.g. [[2 'o] [4 'a] [1 'o]].
er           e# Transliteration. Replaces elements from the sorted copy with
             e# the corresponding element in the shuffled copy in the original list.
             e# [[0 'f] [2 'o] [4 'a] [3 'b] [1 'o] [5 'r]].
Wf=          e# Get the last element of each pair, e.g. "foabor".

5

05AB1E , 17 bytes

žMÃ.r`¹vžMyå_iy}?

Explicação

žMÃ                # get all vowels from input
   .r`             # randomize them and place on stack
      ¹v           # for each in input
        žMyå_i }   # if it is not a vowel
              y    # push it on stack
                ?  # print top of stack

Experimente online!


5

Python 3, 109 bytes

Suporta apenas vogais em minúsculas.

Agradecemos a @Alissa por salvar um byte extra.

import re,random
def f(s):r='[aeiou]';a=re.findall(r,s);random.shuffle(a);return re.sub(r,lambda m:a.pop(),s)

Ideone it!


não seria mais curto se fosse uma função pegar string e retornar essa string com vogais embaralhadas?
Alissa

@ Alissa Obrigado, salvou um byte! : D
Beta Decay

não tenho certeza se ele vai ser mais curta, mas você poderia a.pop(random.randrange(0,len(a))), em vez de baralhar um
Alissa

4

TSQL, 275 bytes

Golfe:

DECLARE @ VARCHAR(99)='the quick brown fox jumps over the lazy dog.'

;WITH c as(SELECT LEFT(@,0)x,0i UNION ALL SELECT LEFT(substring(@,i+1,1),1),i+1FROM c
WHERE i<LEN(@)),d as(SELECT *,rank()over(order by newid())a,row_number()over(order by 1/0)b
FROM c WHERE x IN('a','e','i','o','u'))SELECT @=STUFF(@,d.i,1,e.x)FROM d,d e
WHERE d.a=e.b PRINT @

Ungolfed:

DECLARE @ VARCHAR(max)='the quick brown fox jumps over the lazy dog.'

;WITH c as
(
  SELECT LEFT(@,0)x,0i
  UNION ALL
  SELECT LEFT(substring(@,i+1,1),1),i+1
  FROM c
  WHERE i<LEN(@)
),d as
(
  SELECT 
    *,
    rank()over(order by newid())a,
    row_number()over(order by 1/0)b
  FROM c
  WHERE x IN('a','e','i','o','u')
)
SELECT @=STUFF(@,d.i,1,e.x)FROM d,d e
WHERE d.a=e.b
-- next row will be necessary in order to handle texts longer than 99 bytes
-- not included in the golfed version, also using varchar(max) instead of varchar(99)
OPTION(MAXRECURSION 0) 

PRINT @

Violino


3

Perl, 38 bytes

Inclui +1 para -p

Corra com a frase em STDIN

vawols.pl <<< "programming puzzles & code golf"

vawols.pl:

#!/usr/bin/perl -p
@Q=/[aeiou]/g;s//splice@Q,rand@Q,1/eg

3

Java 7, 243 241 bytes

import java.util.*;String c(char[]z){List l=new ArrayList();char i,c;for(i=0;i<z.length;i++)if("aeiou".indexOf(c=z[i])>=0){l.add(c);z[i]=0;}Collections.shuffle(l);String r="";for(i=0;i<z.length;i++)r+=z[i]<1?(char)l.remove(0):z[i];return r;}

Sim, isso provavelmente pode ser bastante praticado, mas o Java não possui nenhum recurso útil para esse afaik .. Além disso, eu meio que esqueci a variante de array codificada para Collections.shuffle..

Casos não testados e de teste:

Experimente aqui.

import java.util.*;
class M{
  static String c(char[] z){
    List l = new ArrayList();
    char i,
         c;
    for(i = 0; i < z.length; i++){
      if("aeiou".indexOf(c = z[i]) >= 0){
        l.add(c);
        z[i] = 0;
      }
    }
    Collections.shuffle(l);
    String r = "";
    for(i = 0; i < z.length; i++){
      r += z[i] < 1
               ? (char)l.remove(0)
               : z[i];
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c("".toCharArray()));
    System.out.println(c("a".toCharArray()));
    System.out.println(c("cwm".toCharArray()));
    System.out.println(c("the quick brown fox jumps over the lazy dog.".toCharArray()));
    System.out.println(c("abcdefghijklmnopqrstuvwxyz".toCharArray()));
    System.out.println(c("programming puzzles & code golf".toCharArray()));
    System.out.println(c("fatalize".toCharArray()));
    System.out.println(c("martin ender".toCharArray()));
  }
}

Saída possível:

a
cwm
tha queck brown fox jumps evor tho lezy dig.
ebcdifghujklmnopqrstavwxyz
prigrommeng puzzlos & cade golf
fatelazi
mertan inder

1
Que tal reutilizar ino segundo loop?
Frozn 31/08/16

Pensei "por que ele não usou char [] em vez de uma lista", então comecei, mas a falta de Arrays.shuffleme parou ali ...
Olivier Grégoire

Raspou 6 caracteres com alguns pequenos ajustes:import java.util.*;String c(char[]z){List l=new ArrayList();int i=0,j=z.length;for(;i<j;i++)if("aeiou".indexOf(z[i])>=0){l.add(z[i]);z[i]=0;}Collections.shuffle(l);String r="";for(i=0;i<j;i++)r+=z[i]<1?(char)l.remove(0):z[i];return r;}
durron597 /

3

Perl 6 , 65 bytes

{my \v=m:g/<[aeiou]>/;my @a=.comb;@a[v».from]=v.pick(*);@a.join}

Função anônima. Pressupõe entrada em letras minúsculas.

( experimente online )


3

Ruby 45 + 1 = 46 bytes

+1 byte para -psinalizador

a=$_.scan(e=/[aeiou]/).shuffle
gsub(e){a.pop}

3

Braquilog , 39 bytes

@eI:1aToS,I:2f@~:LcS,Tc
.'~e@V;
e.~e@V,

Experimente online!

Explicação

  • Predicado principal:

    @eI        I is the list of chars of the input.
    :1aT       T is I where all vowels are replaced with free variables.
    oS,        S is T sorted (all free variables come first).
    I:2f       Find all vowels in I.
    @~         Shuffle them.
    :LcS,      This shuffle concatenated with L (whatever it may be) results in S.
                 This will unify the free variables in S with the shuffled vowels.
    Tc         Output is the concatenation of elements of T.
    
  • Predicado 1:

    .          Input = Output…
    '~e@V      …provided that it is not a vowel.
    ;          Otherwise Output is a free variable.
    
  • Predicado 2:

    e.         Output is an element of the input…
    ~e@V,      … and it is a vowel.
    

3

Javascript (ES6), 78 76 bytes

s=>s.replace(r=/[aeiou]/g,_=>l.pop(),l=s.match(r).sort(_=>Math.random()-.5))

Economizou 2 bytes graças a apsillers

Versão alternativa proposta pelos apsillers (76 bytes também)

s=>s.replace(r=/[aeiou]/g,[].pop.bind(s.match(r).sort(_=>Math.random()-.5)))

Teste

let f =
s=>s.replace(r=/[aeiou]/g,_=>l.pop(),l=s.match(r).sort(_=>Math.random()-.5))

console.log(f("the quick brown fox jumps over the lazy dog."))


1
Não é uma melhoria (exatamente a mesma pontuação), mas uma uglificação divertida que encontrei: abandone o método l=...inteiramente e use a função bound [].pop.bind(s.match(r).sort(_=>Math.random()-.5)))como o segundo argumento para replace(em vez de uma função de seta). Talvez haja uma melhoria nesse caminho, mas ainda não a encontrei. Se você usou uma linguagem JS-superconjunto que possui o operador de ligação ::, acho que você poderia fazer (s.match(r).sort(_=>Math.random()-.5)))::pop.
Apsillers

3

MATL , 15 bytes

tt11Y2m)tnZr7M(

Experimente online!

Explicação

tt      % Take input string implicitly. Duplicate twice
11Y2    % Predefined string: 'aeiou'
m       % Logical index that contains true for chars of the input that are vowels
)       % Get those chars from the input string. Gives a substring formed by the
        % vowels in their input order
tnZr    % Random permutation of that substring. This is done via random sampling
        % of that many elements without replacement
7M      % Push logical index of vowel positions again
(       % Assign the shuffled vowels into the input string. Display implicitly

3

Japt v2.0a0, 14 13 bytes

ō²f\v
NÌr\v@o

Tente


Explicação

           :Implicit input of string U.
ö²         :Generate a random permutation of U.
  f\v      :Get all the vowels as an array.
\n         :Assign that array to U.
NÌ         :Get the last element in the array of inputs (i.e., the original value of U)
  r\v      :Replace each vowel.
     @o    :Pop the last element from the array assigned to U above.

2

Pitão, 26 bytes

J"[aeiou]"s.i:QJ3.Sf}TPtJQ

Um programa que recebe a entrada de uma sequência de caracteres citada e imprime a sequência aleatória.

Experimente online

Como funciona

J"[aeiou]"s.i:QJ3.Sf}TPtJQ  Program. Input: Q
J"[aeiou]"                  J="[aeiou]"
             :QJ3           Split Q on matches of regex J, removing vowels
                      PtJ   J[1:-1], yielding "aeiou"
                   f}T   Q  Filter Q on presence in above, yielding vowels
                 .S         Randomly shuffle vowels
           .i               Interleave non-vowel and vowel parts
          s                 Concatenate and implicitly print

2

PHP, 144 129 bytes

Usando entrada em minúscula

$r=Aaeiou;$v=str_shuffle(preg_replace("#[^$r]+#",'',$a=$argv[1]));for(;$i<strlen($a);)echo strpos($r,$a[$i++])?$v[$j++]:$a[$i-1];

Explicação:

$r="aeiou"; // set vowels

preg_replace("#[^$r]+#",'',$argv[1]) // find all vowels in input

$v=str_shuffle() // shuffle them

for(;$i<strlen($a);) // run through the text

strpos($r,$a[$i++])?$v[$j++]:$a[$i-1]; // if it's a vowel print the j-th shuffled vowel else print original text

2

Na verdade, 24 bytes

;"aeiou";╗@s@`╜íu`░╚@♀+Σ

Experimente online!

Explicação:

;"aeiou";╗@s@`╜íu`░╚@♀+Σ
;                         dupe input
 "aeiou";╗                push vowels, store a copy in reg0
          @s              split one copy of input on vowels
            @`╜íu`░       take characters from other copy of input where
              ╜íu           the character is a vowel (1-based index of character in vowel string is non-zero)
                   ╚      shuffle the vowels
                    @♀+   interleave and concatenate pairs of strings
                       Σ  concatenate the strings

2

Bash, 75 bytes

paste -d '' <(tr aeoiu \\n<<<$1) <(grep -o \[aeiou]<<<$1|shuf)|paste -sd ''

Pega a string como argumento e imprime o resultado em stdout.

Por exemplo

for x in "" "a" "cwm" \
         "the quick brown fox jumps over the lazy dog." \
         "abcdefghijklmnopqrstuvwxyz" \
         "programming puzzles & code golf" \
         "fatalize" "martin ender"; do
  echo "$x";. sheffle.sh "$x"; echo
done

impressões

<blank line>
<blank line>

a
a

cwm
cwm

the quick brown fox jumps over the lazy dog.
tho quuck brown fix jamps ever the lozy dog.

abcdefghijklmnopqrstuvwxyz
ibcdefghajklmnopqrstuvwxyz

programming puzzles & code golf
progremmong pazzlus & cedo gilf

fatalize
fetilaza

martin ender
mertan endir

2

Bash, 89

Supõe que todas as entradas sejam minúsculas.

a=`tee z|grep -o [aeiou]`
[ -n "$a" ]&&tr `tr -d \ <<<$a` `shuf -e $a|tr -d '
'`<z||cat z

2

PowerShell v3 +, 155 99 bytes

param([char[]]$n)$a=$n|?{$_-match'[aeiou]'}|sort{random};-join($n|%{if($_-in$a){$a[$i++]}else{$_}})

Grandes adereços para Ben Owen para o golfe de 56 bytes

Recebe entrada $n, esperando todas as letras minúsculas, lança-a imediatamente como uma charmatriz.

Nós canalizamos isso em uma Where-Objectcláusula para extrair os elementos que -matchuma vogal, canalizamos Sort-Objectcom {Get-Random}o mecanismo de classificação. Chamar Get-Randomsem qualificadores retornará um número inteiro entre 0e [int32]::MaxValue- ou seja, atribuir pesos aleatórios a cada elemento em tempo real. Armazenamos as vogais aleatórias em $a.

Finalmente, nós passamos $n. Para cada elemento, |%{...}se o caractere atual estiver em algum lugar -in $a, enviaremos o próximo elemento para $após-incremento $ida próxima vez. Caso contrário, produzimos o caractere atual. Tudo isso é encapsulado em parênteses e edificado -joinem uma string. Essa string é deixada no pipeline e a saída é implícita na conclusão do programa.

Casos de teste

PS C:\Tools\Scripts\golfing> 'a','cwm','the quick brown fox jumps over the lazy dog.','abcdefghijklmnopqrstuvwxyz','programming puzzles & code golf','fatalize','martin ender'|%{.\vawols.ps1 $_}
a
cwm
thu qaeck brown fix jomps ovor thu lezy deg.
abcdofghejklmnupqrstivwxyz
prugrammong pizzles & code golf
fitaleza
mertin endar

Você pode salvar muitos bytes aqui iterando $nos caracteres de e correspondendo em cada vogal para produzir a charmatriz de vogais. Algo como:$a=[char[]]$n|?{$_-match'[aeiou]'}|sort{random}
Ben Owen

@BenOwen Puta merda, sim. Obrigado pelo golfe de 56 bytes. Para a minha vida, eu simplesmente não conseguia descobrir uma maneira melhor de construir $a.
AdmBorkBork 01/09/16

2

Python 3, 106 bytes

Apenas em minúsculas.

import re,random
def f(s):s=re.split('([aeiou])',s);v=s[1::2];random.shuffle(v);s[1::2]=v;return''.join(s)

1

PHP> = 5.3 , 139 136 bytes (e nenhum erro foi lançado)

array_map(function($a,$b){echo$a.$b;},preg_split("/[aeiou]/",$s=$argv[1]),str_split(str_shuffle(implode(preg_split("/[^aeiou]/",$s)))));

1

K (oK) , 29 bytes

Solução:

{x[a:&x in"aeiou"]:x@(-#a)?a}

Experimente online!

Exemplos:

"pregrommeng pizzlas & codo gulf"
{x[a:&x in"aeiou"]:x@(-#a)?a}"programming puzzles & code golf"
"pregremmong puzzlos & coda gilf"
{x[a:&x in"aeiou"]:x@(-#a)?a}"programming puzzles & code golf"
"pregrommeng pazzlos & cidu golf"

Explicação:

Encontre os locais das vogais e substitua-os pelas vogais desenhadas em uma ordem aleatória.

{x[a:&x in"aeiou"]:x@(-#a)?a} / the solution
{                           } / anonymous function with input x
 x[              ]            / index into x at these indices
      x in"aeiou"             / is character a vowel
     &                        / indices where true
   a:                         / assign to add
                  :           / assign
                          ?a  / draw randomly from a
                     (   )    / do this together
                       #a     / count length of a
                      -       / negate (draws from list, no duplication)
                   x@         / apply these indices to input


Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.