Sheffle tho vawols ureund!


42

Mengingat string input, output string dengan semua vokal a, e, i, odan ubertukar secara acak antara satu sama lain.

Sebagai contoh, dalam string this is a test, ada 4 vokal: [i, i, a, e]. [a, i, e, i]Oleh karena itu pengocokan vokal yang valid dapat menghasilkan output thas is e tist.

Tentang pengocokan

Semua pengocokan akan memiliki kemungkinan yang sama jika kita menganggap vokal yang sama berbeda . Untuk contoh di atas, 24 pengocokan tersebut dimungkinkan:

[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 ]

Masing-masing harus sama mungkin.

Anda tidak dapat mencoba mengacak acak seluruh string hingga menemukan satu di mana semua vokal berada di tempat yang tepat. Singkatnya, waktu menjalankan kode Anda akan konstan jika inputnya konstan.

Masukan dan keluaran

  • Anda dapat mengasumsikan bahwa semua huruf dalam input akan berupa huruf kecil atau huruf besar. Anda juga dapat mendukung casing campuran, meskipun ini tidak akan memberi Anda bonus apa pun.

  • Input akan selalu terdiri dari karakter ASCII yang dapat dicetak. Semua karakter yang ada di input harus dalam output, hanya vokal yang harus dikocok dan tidak ada yang lain.

  • Masukan bisa kosong. Tidak ada jaminan bahwa input akan mengandung setidaknya satu vokal atau setidaknya satu non-vokal.

  • Anda dapat mengambil input dari STDIN, sebagai parameter fungsi, atau yang serupa.

  • Anda dapat mencetak output ke STDOUT, mengembalikannya dari fungsi, atau yang serupa.

Uji kasus

Baris pertama adalah input yang diberikan. Baris kedua adalah salah satu output yang mungkin.

<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

Mencetak gol

Ini adalah , kecuali untuk kemeja byte .


17
Anda orang Inggris / Amerika dan kekurangan Anda ysebagai vokal ..;)
Kevin Cruijssen

6
@KevinCruijssen Saya bukan penutur asli dan saya juga akan mempertimbangkan ymenjadi vokal, tetapi tantangan terakhir di mana saya katakan yadalah vokal. Saya ditanya mengapa saya memilih itu!
Fatalkan

7
@KevinCruijssen, huruf bukan vokal: suara.
Peter Taylor

6
+1 untuk cwm. Menjaga pendakian gunung dan / atau Welsh tetap hidup;)
Beta Decay

2
@KevinCruijssen Jangan memiliki co w tentang vo w els yang tidak umum dianggap begitu.
corsiKa

Jawaban:


13

Jelly , 15 byte

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

Cobalah online!

Bagaimana itu bekerja

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.

Mengapa ini tampak cukup lambat dibandingkan dengan jawaban lain?
Fatalkan

Jelly mengimpor SymPy dan NumPy sebelum yang lainnya. Program ini dan program kosong kira-kira memiliki waktu eksekusi yang sama.
Dennis

15
Sebelum ada yang bertanya, euoi adalah seruan kegembiraan yang penuh gairah dalam kebahagiaan Bacchic kuno .
Dennis

5
@ Dennis Karena penasaran, mengapa Jelly membangun kata-kata kamus? Dari mana ia mendapatkan kata-kata kamus ini?
Kevin Cruijssen

1
@KevinCruijssen Ketika saya mendesain Jelly, sudah ada beberapa bahasa golf yang menggunakan shoco , dan hanya menggunakan kamus bahasa Inggris sepertinya cara yang baik untuk memperbaiki ide itu. Saya menggunakan file /usr/share/dict/wordsdari komputer saya dan memasukkannya ke dalam juru bahasa Jelly.
Dennis

17

R, 92 91

Tidak dapat berkomentar, jadi saya menambahkan jawaban saya sendiri walaupun sangat mirip dengan jawaban @ Andreï Kostyrka (percaya atau tidak tetapi muncul secara mandiri).

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

Tidak disatukan

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

Disimpan satu byte berkat @Vlo

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

5
Jujur, saya tidak bisa percaya. Hanya bercanda. Trik yang bagus untuk menghemat beberapa byte!
Andreï Kostyrka

Jujur saja, saya tidak mencuri ide-ide Anda untuk golf jawaban saya lebih lanjut.
Andreï Kostyrka

3
Hehe, harus mendapatkan mereka upvotes manis sehingga saya bisa berkomentar;)
Billywob

Simpan satu byte dengan penugasan in-line 91 bytes=strsplit(readline(),"")[[1]];s[v]=sample(s[v<-s%in%c("a","e","i","o","u")]);cat(s,sep="")
Vlo

Simpan byte lain dengan menggunakan el()alih-alih [[1]].
Andreï Kostyrka

11

R, 99 98 89 byte

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

Tampaknya menjadi solusi yang dapat dibaca manusia pertama! Terima kasih kepada Giuseppe karena telah menghemat 9 byte!

Kasus uji:

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

Tampaknya tidak ada cara untuk membuat penugasan variabel internal (di dalam, seperti, cat), dan lagi beberapa orang akan membuktikan bahwa saya salah ...


2
letters[c(1,5,9,15,21)]adalah 1 byte lebih lama, dan OEIS A161536 dan A215721 tampaknya sedikit membantu juga.
Andreï Kostyrka

Bukankah z=grepl("[aeiou]",x)lebih pendek?
Giuseppe

@ Giuseppe Anda melakukannya lagi! Terima kasih.
Andreï Kostyrka

10

CJam, 23 byte

lee_{"aeiou"&},_mrerWf=

Cobalah online!

Penjelasan

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 byte

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

Penjelasan

ž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

Cobalah online!


5

Python 3, 109 byte

Hanya mendukung vokal huruf kecil.

Terima kasih kepada @Alissa karena telah menyimpan byte tambahan.

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)

Ide itu!


bukankah itu akan lebih pendek jika itu adalah fungsi yang mengambil string dan mengembalikan string itu dengan vokal yang dikocok?
Alissa

@ Alissa Terima kasih, ini menghemat satu byte! : D
Beta Decay

tidak yakin apakah itu akan lebih pendek, tetapi Anda bisa a.pop(random.randrange(0,len(a)))bukannya mengocok
Alissa

4

TSQL, 275 byte

Golf:

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 @

Tidak Disatukan:

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 @

Biola


3

Perl, 38 byte

Termasuk +1 untuk -p

Jalankan dengan kalimat di 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 byte

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;}

Ya, ini mungkin bisa golf sedikit, tetapi Java tidak memiliki built-in berguna untuk afaik ini .. Juga, saya agak lupa codegolfed array-varian untuk Collections.shuffle..

Kasus yang tidak disatukan & uji:

Coba di sini.

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()));
  }
}

Output yang mungkin:

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

1
Bagaimana kalau menggunakan kembali ipada loop kedua?
Frozn

Saya pikir "mengapa dia tidak pergi dengan char [] bukan Daftar", jadi saya mulai, tetapi kurangnya Arrays.shufflemenghentikan saya di sana ...
Olivier Grégoire

Mencukur 6 karakter dengan sedikit 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;}
perubahan

3

Perl 6 , 65 byte

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

Fungsi anonim. Mengasumsikan input huruf kecil.

( coba online )


3

Ruby 45 + 1 = 46 byte

+1 byte untuk -pbendera

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

3

Brachylog , 39 byte

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

Cobalah online!

Penjelasan

  • Predikat utama:

    @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.
    
  • Predikat 1:

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

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

3

Javascript (ES6), 78 76 byte

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

Disimpan 2 byte berkat apsillers

Versi alternatif yang diusulkan oleh apsillers (76 bytes juga)

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

Uji

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
Bukan perbaikan (skor yang sama persis), tetapi uglifikasi menyenangkan yang saya temukan: jatuhkan l=...seluruhnya dan gunakan fungsi terikat [].pop.bind(s.match(r).sort(_=>Math.random()-.5)))sebagai argumen kedua replace(bukan fungsi panah). Mungkin ada perbaikan yang ditemukan di jalan itu, tapi saya belum menemukannya. Jika Anda menggunakan bahasa JS-superset yang memiliki operator ikat ::, saya pikir Anda bisa melakukannya (s.match(r).sort(_=>Math.random()-.5)))::pop.
apsillers

3

MATL , 15 byte

tt11Y2m)tnZr7M(

Cobalah online!

Penjelasan

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 byte

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

Cobalah


Penjelasan

           :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

Pyth, 26 byte

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

Suatu program yang mengambil input dari string yang dikutip dan mencetak string yang diacak.

Cobalah online

Bagaimana itu bekerja

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 byte

Menggunakan input huruf kecil

$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];

Penjelasan:

$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

Sebenarnya, 24 byte

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

Cobalah online!

Penjelasan:

;"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 byte

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

Mengambil string sebagai argumen dan mencetak hasilnya ke stdout.

Misalnya

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

cetakan

<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

Mengasumsikan semua input menjadi huruf kecil.

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 byte

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

Alat peraga besar untuk @ Ben Owen untuk golf 56-byte

Mengambil input $n, mengharapkan semua huruf kecil, segera melemparkannya sebagai char-array.

Kami menyalurkannya ke dalam Where-Objectklausa untuk menarik elemen-elemen yang -matchvokal, menyalurkannya Sort-Objectdengan {Get-Random}sebagai mekanisme penyortiran. Panggilan Get-Randomtanpa kualifikasi akan menghasilkan bilangan bulat antara 0dan [int32]::MaxValue- yaitu, menugaskan bobot acak untuk setiap elemen dengan cepat. Kami menyimpan vokal acak ke $a.

Akhirnya, kami mengulang $n. Untuk setiap elemen,, |%{...}jika karakter saat ini ada di suatu tempat -in $a, kami menampilkan elemen berikutnya $a, setelah kenaikan $iuntuk waktu berikutnya. Jika tidak, kami menampilkan karakter saat ini. Itu semua diringkas dalam parens dan diedit -joinmenjadi sebuah string. String itu ditinggalkan di jalur pipa, dan output tersirat pada kesimpulan program.

Uji kasus

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

Anda dapat menyimpan banyak byte di sini dengan mengulangi $nkarakter-karakternya dan mencocokkan setiap vokal untuk menampilkan char-array vokal sebagai gantinya. Sesuatu seperti:$a=[char[]]$n|?{$_-match'[aeiou]'}|sort{random}
Ben Owen

@ Benwen Holy dang, ya. Terima kasih untuk golf 56-byte. Untuk kehidupan saya, saya tidak bisa menemukan cara yang lebih baik untuk membangun $a.
AdmBorkBork

2

Python 3, 106 byte

Huruf kecil saja.

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 byte (dan tidak ada kesalahan yang terjadi)

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 byte

Larutan:

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

Cobalah online!

Contoh:

"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"

Penjelasan:

Temukan lokasi vokal dan ganti dengan vokal yang digambar dalam urutan acak.

{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


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.