44
\$\begingroup\$

This is much more advanced than How to randomize letters in a word and Cambridge Transposition because of the rule about which letters may be swapped with which. A simple regex will not suffice here.


It is well known that a text can still be read while the innards of its words have been scrambled, as long as their first and last letters plus their overall outlines remain constant. Given a printable Ascii+Newline text, scramble each word according to these rules:

  1. Scrambling must be (pseudo) random.

  2. A word is a sequence of the Latin characters, A through Z.

  3. Only initial letters will ever be uppercase.

  4. The first and last letters must stay untouched.

  5. When scrambling, only letters within one of the following groups may exchange places:

    1. acemnorsuvwxz

    2. bdfhkl

    3. gpqy

    4. it

    5. j (stays in place)

Example

Srcmable wrods while psrrnveieg their oeiltnus

It is well known that a txet can still be read while the inrands of its wrods have been srcambled, as long as their fisrt and last letters plus their ovaerll ontliues raemin canstnot. Given a patnirlbe Acsii+Nwnliee txet, samrclbe ecah word anoccdirg to these relus:

  1. Smncrbliag must be (pusedo) rondam.

  2. A wrod is a seqencue of the Latin chreratacs, A thurogh Z.

  3. Only iniital lrttees will eevr be uppcsaere.

  4. The fisrt and lsat lettres must stay uctoenhud.

  5. When sarnclbimg, only letters wihtin one of the fwllnoiog guorps may ecxhange plaecs:

    1. aneusvrowxmcz

    2. bhkfdl

    3. gqpy

    4. it

    5. j (stays in plcae)

Emxaple

\$\endgroup\$
  • \$\begingroup\$ t is supposed to be shorter than h although many people do not write it so. \$\endgroup\$ – Leaky Nun May 10 '17 at 6:00
  • \$\begingroup\$ @LeakyNun I know, but are you suggest removing t from group 2? Or maybe putting t in a group 4 with i? \$\endgroup\$ – Adám May 10 '17 at 6:02
  • \$\begingroup\$ The latter would be fine. \$\endgroup\$ – Leaky Nun May 10 '17 at 6:08
  • \$\begingroup\$ may the runtime be theoretically unbounded? (like random tries until something is right) \$\endgroup\$ – Sarge Borsch May 10 '17 at 9:40
  • 1
    \$\begingroup\$ printable/patnirlbe isn't quite readable. I think the i/t swap is to blame. Hmm... paintrlbe No that didn't help either. It's probably the pr/pa swap, then. The outline maintains, but I think that I read "pr" and "pa" as being semantically(?) 1 letter. prtnialbe Ah yes. That did it. Not sure I can offer a fix to the algorithm though. \$\endgroup\$ – Draco18s May 10 '17 at 18:20

12 Answers 12

9
\$\begingroup\$

Jelly, 80 74 bytes

-2 bytes by moving from czar + vex + mow + sun to czar + vexes + unmown (the repeated es and ns are not a problem)
-1 byte using Tị rather than ȦÐf
-1 byte using Œle€Øa rather than i@€ØB>⁵
-2 bytes by reconfiguring the layout a little

Tị
TẊị⁹ż@œp
e€ç⁸F
W;“HọƊṘ€.`]HɲøƁḤ0ẉlfrøj⁷»Ḳ¤ç/
Ḣ,ṪjÇḟ0
Œle€Øað¬œpÇ€ÑżœpÑ¥

A full program taking a character list (or Python formatted string), which prints the result of the scrambling.

Try it online!

A huge amount of difficulty for Jelly here it seems (either that or I have missed a trick, which has been known to happen!) This will surely be beaten by languages with better string manipulation like Retina(no random functionality) or 05ab1e.

How?

Tị - Link 1, get truthy items: list a
T  - truthy indexes of a
 ị - index into a

TẊị⁹ż@œp - Link 2, selective shuffle: list a, list b
T        - truthy indexes of a (those indexes that may be shuffled in b)
 Ẋ       - random shuffle
   ⁹     - link's right argument, b
  ị      - index into (gets the shuffled values)
      œp - partition b at truthy indexes of a
    ż@   - zip with reversed @rguments (place shuffled values - yields a list of lists)

e€ç⁸F - Link 3, value selective shuffle: list a, list b
e€    - c exists in b? for €ach c in a (1s where b has shuffle-able characters, else 0s)
   ⁸  - link's left argument, a
  ç   - call the last link (2) as a dyad
    F - flatten the result (from the yielded list of lists to one list)

W;“HọƊṘ€.`]HɲøƁḤ0ẉlfrøj⁷»Ḳ¤ç/ - Link 4, perform all shuffles on a word's innards: list x
W                             - wrap x in a list
                          ¤   - nilad followed by link(s) as a nilad:
  “HọƊṘ€.`]HɲøƁḤ0ẉlfrøj⁷»     -   compression of s(bdfhkl)+d( czar)+d(vexes)+d(unmown)+s( gpqy)+d( ti)
                              -     where d() looks up a word in Jelly's dictionary and s() adds a string to the compressed output.
                         Ḳ    -   split on spaces: ["bdfhkl","czarvexesunmown","gpqy","ti"]
                           ç/ - reduce by last link (3) as a dyad (shuffles by each in turn)

Ḣ,ṪjÇḟ0 - Link 5, shuffle a word: list w
Ḣ       - head w (yields the leftmost character and modifies w)
  Ṫ     - tail w (yields the rightmost character and modifies w)
 ,      - pair
        -   Note: head and tail yield 0 when w is empty, so ['a'] -> ["a",0] and [] -> [0,0]
    Ç   - call the last link (4) as a monad (with the modified w)
   j    - join
     ḟ0 - filter discard zeros (thus single or zero letter words pass through unchanged)

Œle€Øað¬œpÇ€ÑżœpÑ¥ - Main link: list s
Œl                 - convert s to lowercase, say t
    Øa             - lowercase alphabet, say a
  e€               - c exists in a? for €ach c in t
      ð            - dyadic chain separation (call that u)
       ¬           - not (vectorises across u), say v
        œp         - partition s at truthy indexes of v (extract words, plus empty lists from within strings of non-alphabetic characters)
          Ç€       - call the last link (5) as a monad for €ach (shuffle their innards)
            Ñ      - call the next link (1) as a monad (only keep the actual words)
                 ¥ - last two links as a dyad:
              œp   -   partition s at truthy indexes of u (get the non-words, plus empty lists from within strings of alphabetic characters)
                Ñ  -   call the next link (1) as a monad (only keep actual non-words)
             ż     - zip together
                   - implicit print
\$\endgroup\$
  • \$\begingroup\$ It's actually harder than I thought. \$\endgroup\$ – Leaky Nun May 10 '17 at 11:54
  • \$\begingroup\$ @LeakyNun welp it took me much longer than 10 minutes to grapple with it. \$\endgroup\$ – Jonathan Allan May 10 '17 at 11:54
  • 1
    \$\begingroup\$ @JonathanAllan Yeah, it's been on there for ages, and is probably going to be part of the next release, because this has been bugging me many times. \$\endgroup\$ – Martin Ender May 10 '17 at 12:18
  • 1
    \$\begingroup\$ czar + vex + mow + sun \$\endgroup\$ – Adám May 10 '17 at 12:59
  • 3
    \$\begingroup\$ @Adám dictionary lookups to form acemnorsuvwxz. I will write up commented code at some point too. \$\endgroup\$ – Jonathan Allan May 10 '17 at 12:59
5
\$\begingroup\$

PHP, 278 Bytes

<?=preg_replace_callback("#\pL\K(\pL+)(?=\pL)#",function($t){preg_match_all("#([^bdf-lpqty])|([bdfhkl])|([gpqy])|([it])|(j)#",$t[0],$p);foreach($p as$v){$k++?$c=array_keys($n=array_filter($v)):$o=[];!$n?:shuffle($n)&&$o+=array_combine($c,$n);}ksort($o);return join($o);},$argn);

Try it online!

Expanded

echo preg_replace_callback("#\pL\K(\pL+)(?=\pL)#" # patter \pL is shorter as [a-z]
,function($t){  # replacement function beginning
  preg_match_all("#([^bdf-lpqty])|([bdfhkl])|([gpqy])|([it])|(j)#",$t[0],$p); # makes groups with the regex. group 0 is the whole substring
  foreach($p as$v){ # loop through groups
    $k++?$c=array_keys($n=array_filter($v)):$o=[]; # group 0 make new empty replacement array in the other case filter the group remove empty values. 
    #You gain an array with the keys as position in the substring and the values
    #store the key array and the values array
    !$n?:shuffle($n)&&$o+=array_combine($c,$n); 
    #if values shuffle the values and make a new array with the keys and the shuffled values and merge the new array to the replacement array
  }
  ksort($o); # sort the replacement array ascending positions 
  return join($o); # return the replacement as string
},$argn);

functions

array_combine

array_filter

array_keys

ksort

preg_replace_callback

shuffle

\$\endgroup\$
  • \$\begingroup\$ Tip: You could use the "disable output cache" setting on TIO, rather than running the code a few times. I just ran it with the example - All good! \$\endgroup\$ – Jonathan Allan May 10 '17 at 12:35
  • \$\begingroup\$ @JonathanAllan Thank You for the tip with the cache. It was hard enough to find a way to solve this \$\endgroup\$ – Jörg Hülsermann May 10 '17 at 12:41
5
\$\begingroup\$

Pyth, 79 bytes

sm?td++hduuXNhTeTC,f@@GTHUG.S@HGG+-GJ."by❤jã~léܺ"cJ\jPtdedd:jb.z"([A-Za-z]+)"3

where is U+0018.

Try it online!

Sample

It is well knwon that a text can still be raed while the irnands of its wrods have been seraclbmd, as long as their first and last lettres plus their oaervll ontliues rmeain conntsat. Given a text, sacmrble each wrod acrncdiog to thsee relus:

  1. Scamrlbing must be (puesdo) rnadom.

  2. A word is a suqencee of the Latin chraectars, A thuorgh Z.

  3. Only iaitinl lettres will eevr be uppaersce.

  4. The first and last lettres msut stay uotcnuhed.

  5. When srancblimg, only lettres wiihtn one of the follnwiog guorps may enxhcage plecas:

    1. amsuvrcnoxewz

    2. bhfkdl

    3. gpqy

    4. it

    5. j (stays in place)

\$\endgroup\$
  • \$\begingroup\$ Can't you save with \pL instead of [A-Za-z]? \$\endgroup\$ – Adám May 10 '17 at 13:36
  • \$\begingroup\$ @Adám What is \pL? \$\endgroup\$ – Leaky Nun May 10 '17 at 13:38
  • \$\begingroup\$ Any character with the property of being a Letter. \$\endgroup\$ – Adám May 10 '17 at 13:38
  • \$\begingroup\$ I don't think it works here... \$\endgroup\$ – Leaky Nun May 10 '17 at 13:41
  • \$\begingroup\$ wouldn't \w be enough? \$\endgroup\$ – Sarge Borsch May 10 '17 at 13:41
5
\$\begingroup\$

JavaScript 176 bytes

t.replace(/\B(\w+)\B/g,b=>{return[/[acemnorsuvwxz]/g,/[bdfhkl]/g,/[gpqy]/g,/[it]/g].forEach(d=>{g=b.match(d),b=b.replace(d,c=>{return g.splice(Math.random()*g.length,1)})}),b})

Method:

  1. RegExp iterates over the centre of each word (/\B(\w+)\B/g) using 1st replace fn.

  2. 1st replace fn iterates an array of RegExp's for each letter-group (/[bdfkhl/g, /[gqpy]/g, etc..).

  3. Each iteration builds a temp array of word-centre's characters appearing in current letter-group.

  4. Each iteration then uses current letter-group's RegExp to iterate over entire word-centre, using a 2nd replace fn.

  5. 2nd replace fn randomly splices the temp array, removing a random character and returning it.

Demo:

Run it in JSFiddle: https://jsfiddle.net/CookieJon/bnpznb7r/

\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG. Amazing first answer. However, I think you need \pL(\pL+)\pL rather than \B(\w+)\B to exclude digits and underscore. \$\endgroup\$ – Adám May 11 '17 at 7:21
  • \$\begingroup\$ Ah, thanks! Must admit regex is not my bag (I have to look up the reference EVERY time I use it!) I can swallow the 3 extra characters... will update my answer shortly thanks again. :-) \$\endgroup\$ – Bumpy May 11 '17 at 7:28
  • 1
    \$\begingroup\$ Incredible first answer! :) A few, quick improvements for you to get you down to 155 bytes, including @Adáms correction above: t=>t.replace(/\B[a-z]+\B/gi,b=>([/[acemnorsuvwxz]/g,/[bdfhkl]/‌​g,/[gpqy]/g,/[it]/g]‌​.map(d=>b=b.replace(‌​d,c=>g.splice(new Date%g.length,1),g=b.match(d))),b)) \$\endgroup\$ – Shaggy May 11 '17 at 11:18
  • \$\begingroup\$ @Shaggy I think b=>[...].map(...)&&b saves another byte. Also I'm not sure your i is necessary. \$\endgroup\$ – Neil May 11 '17 at 21:35
  • \$\begingroup\$ If @Adám is going to be strictly picky with his word definition then you'll need to use t.replace(/[A-Za-z]([a-z]+)(?=[a-z])/g,(w,b)=>...w[0]+b...) or some such. \$\endgroup\$ – Neil May 11 '17 at 21:39
2
\$\begingroup\$

C, 453, 356 369 bytes

#define F for
#define M rand()%s+1+q
char a[256],*b=" acemnorsuvwxz\1bdfhkl\1gpqy\1it\1j";g(c,t)char*c,*t;{static int i,j,k,w,v,n,q,s,r;r=-1;if(c&&t){strcpy(c,t);if(!k)F(j=i=k=1;b[i];++i)b[i]-1?(a[b[i]]=j):++j;F(r=i=0;c[i];){F(;isspace(c[i]);++i);F(q=i;!isspace(c[i])&&c[i];++i);F(s=v=i-q-2;--v>0;)if(a[c[j=M]]==a[c[w=M]]&&a[c[j]])n=c[j],c[j]=c[w],c[w]=n;}}return r;}

ungolf with comments

// Input in the arg "t" result in the arg "c"
// NB the memory pointed from c has to be >= memory pointed from t
//    the char is 8 bit
#define F for
#define M rand()%s+1+q
char a[256], *b=" acemnorsuvwxz\1bdfhkl\1gpqy\1it\1j";
   g(c,t)char*c,*t;
   {static int i,j,k,w,v,n,q,s,r;
    r=-1;
    if(c&&t)
      {strcpy(c,t);                         // copy the string in the result space
       if(!k)
         F(j=i=k=1;b[i];++i)
             b[i]-1?(a[b[i]]=j):++j;        // ini [possible because at start k=0]
       F(r=i=0;c[i];)
         {F(;isspace(c[i]);++i);            //skip spaces
                                            // the start q the end+1 i
          F(q=i;!isspace(c[i])&&c[i];++i);  //skip word
          F(s=v=i-q-2;--v>0;)               //loop for swap letters of the same set
            if(a[c[j=M]]==a[c[w=M]]&&a[c[j]])
                n=c[j],c[j]=c[w],c[w]=n;
         }
      }
   return r;
  }


#include <stdio.h>
#define G(x,y) if(x)goto y
main()
{char a[256],r[256];
l1:
 gets(a);// i would know the string lenght<256
 g(r,a);
 printf("%s\n",r);
 G(*a,l1);
}
\$\endgroup\$
1
\$\begingroup\$

Python 3.6, 349 340 bytes

from itertools import *
from random import *
import re
def S(s):
    C=lambda c:len(list(takewhile(lambda x:c not in x,('j','it','gqpy','bhkfdl'))));L=[];B=[[]for i in range(5)]
    for l in s:c=C(l);L+=[c];B[c]+=[l];shuffle(B[c])
    return''.join(B[n].pop()for n in L)
A=lambda t:re.sub('[A-Za-z]{3,}',lambda x:x[0][0]+S(x[0][1:][:-1])+x[0][-1],t)

Indented with tabs. The function is named A. It doesn't use brute force, the runtime is deterministic, as OP asked.

\$\endgroup\$
1
\$\begingroup\$

Mathematica 232 Bytes

StringReplace[#,x:Repeated[WordCharacter,{2,∞}]:>""<>(s=StringTake)[x,{i,i}~Table~{i,StringLength@x}/.Flatten[Thread[#->RandomSample@#]&/@(StringPosition[x~s~{2,-2},#]+1&/@Characters@{"acemnorsuvwxz","bdfhkl","gpqy","it","j"})]]]&

The basic idea is to permute the subsets corresponding to the 4 distinct character groups. Probably room for improvement.

\$\endgroup\$
1
\$\begingroup\$

C, 306 282 Bytes

c,o,d,e,g;l(char*f){char*s[]={"aneusvrowxmcz","bhkfdl","gqpy","it",0},**h,*i,*t;for(i=f;*i;){if(isalpha(*i)){t=i;while(*i&&isalpha(*i))i++;e=i-t-2;for(h=s;*h&&e;*h++){for(c=999;--c;){d=1+rand()%e,o=1+rand()%e;if(strchr(*h,t[d])&&strchr(*h,t[o]))g=t[d],t[d]=t[o],t[o]=g;}}}else++i;}}

Try it online

Ungolfed:

int func(char*p) 
{
    char *groups[] = {"aneusvrowxmcz","bhkfdl","gqpy","it",0}, **g, *s, *t;
    int n,r,i,l,o;

    for (s = p; *s;)
    {
        if (isalpha(*s))
        {
            t = s;
            while (*s && isalpha(*s))
                s++;
            // start scrambling
            l = s - t - 2;
            for(g=groups; *g && l; *g++)
            {
                for(n=999;--n;)
                {
                    i = 1 + rand() % l;
                    r = 1 + rand() % l;
                    if (strchr(*g, t[i]) && strchr(*g, t[r]))
                    {
                        o=t[i];
                        t[i]=t[r];
                        t[r]=o;
                    }
                }
            }
            // end scrambling
        }
        else 
            s++;
    }
}
\$\endgroup\$
  • \$\begingroup\$ Why would you like to do 999 swap in a word? Do you know that one word of one char has l=-1 and this possibly means that it begin to do 999 possible swap using 1 + rand() % -1 so random write in 2 giga of memory... But possible i see it wrong.... \$\endgroup\$ – RosLuP May 12 '17 at 14:45
  • \$\begingroup\$ There's unfortunately no magic regarding the use of 999. It's just 1 byte less than 1000 :) \$\endgroup\$ – Johan du Toit May 12 '17 at 15:02
  • \$\begingroup\$ In gcc it seems rand()%(-1) return 0 the first 2 time I tried it. so possible no swap of random 2giga space...% of int is not the % of unsigned... \$\endgroup\$ – RosLuP May 12 '17 at 15:19
  • \$\begingroup\$ @RosLup, I'm sorry but I don't follow what you are saying.. \$\endgroup\$ – Johan du Toit May 12 '17 at 15:42
1
\$\begingroup\$

JavaScript (ES6), 380 327 311 294 Bytes

(298 282 265 Bytes excluding the rules)

Thanks to @Shaggy for the useful tips!

((b,d)=>b.replace(/\B[a-z]+\B/gi,f=>(g=>(g.map(j=>(h=d.slice(0,~(rind=d.indexOf(j))?rind:-1),~rind?h.split`,`.length-1:-1)).map((j,k,l,m=[])=>{l.map((n,o)=>n==j?m.push(o):0),sub=m[new Date%(m.length-1)]||k,tmp=g[sub],g[sub]=g[k],g[k]=tmp}),g.join``))([...f])))(s,"aneusvrowxmcz,bhkfdl,gqpy,it");

var f = ((b,d)=>b.replace(/\B[a-z]+\B/gi,f=>(g=>(g.map(j=>(h=d.slice(0,~(rind=d.indexOf(j))?rind:-1),~rind?h.split`,`.length-1:-1)).map((j,k,l,m=[])=>{l.map((n,o)=>n==j?m.push(o):0),sub=m[new Date%(m.length-1)]||k,tmp=g[sub],g[sub]=g[k],g[k]=tmp}),g.join``))([...f])))

var s="Let there be scrambling";
console.log(s);
console.log(f(s,"aneusvrowxmcz,bhkfdl,gqpy,it"))

s="It is well known that a text can still be read while the innards of its words have been scrambled, as long as their first and last letters plus their overall outlines remain constant. Given a printable Ascii+Newline text, scramble each word according to these rules";
console.log(s);
console.log(f(s,"aneusvrowxmcz,bhkfdl,gqpy,it"))

Function f takes in a string of any kind (single word, multiple words, multiple words with signs in it - which it interprets as word-breaking) and an array a string of "rules" of any length separated by commas.

That array of rules, in the case of your question, would be ["aneusvrowxmcz", "bhkfdl", "gqpy", "it"] "aneusvrowxmcz,bhkfdl,gqpy,it"

Some letters don't get mixed even though they could, since you stated in your question that letters "may exchange spaces". If I misinterpreted it, I can change the code to always scramble letters that match the rules.

I know this is an enormous amount of bytes and it won't be able to compete with golfing languages, but I wanted to try anyway, hope you like it :)

Human-readable non-uglified code:

((txt,rules)=>txt.replace(/\B[a-z]+\B/gi,wo=>((w=>(w.map(c=>(h=rules.slice(0, ~(rind=rules.indexOf(c))?rind:-1),~rind?(h.split`,`.length-1):-1)).map((e,i,arr,a=[])=>{
    arr.map((x,i)=>(x==e)?a.push(i):0),
    sub=a[new Date%(a.length-1)]||i,
    tmp=w[sub],
    w[sub]=w[i],
    w[i]=tmp
}),w.join``))([...wo]))))(str, "aneusvrowxmcz,bhkfdl,gqpy,it")
\$\endgroup\$
  • 1
    \$\begingroup\$ The OP rules have to be included in byte count. By may, I meant have a chance to. \$\endgroup\$ – Adám May 10 '17 at 14:50
  • 1
    \$\begingroup\$ Welcome to PPCG :) You can definitely golf a lot off this. \$\endgroup\$ – Shaggy May 10 '17 at 14:54
  • 1
    \$\begingroup\$ I was going to try to golf this down for you but, given how much can be done with it, I ran out of time so instead I'll point you here and here to help get you started. \$\endgroup\$ – Shaggy May 10 '17 at 15:09
  • 1
    \$\begingroup\$ A few quick pointers, though: 01) Get rid of all the vars an lets. 02) Unless it's a recursive function, no need to include the variable declaration (f=) in your byte count. 03) Use currying when a function has 2 parameters (b=>d=> instead of (b,d)=>) and call your function with f(b)(d). 04) You have the i flag so no need to include A-Z in your regex. 05) You can use indexOf or search on a string, without splitting it into an array. \$\endgroup\$ – Shaggy May 10 '17 at 15:15
  • 1
    \$\begingroup\$ How does suggestion 03 save characters? They look the same to me. \$\endgroup\$ – Steve Bennett May 12 '17 at 4:21
0
\$\begingroup\$

Clojure, 326 322 324 bytes

Update 1: replaced (map(fn[[k v]]...)...) with (for[[k v]...]...)

Update 2: fixed regex, using \pL instead of \w etc.

#(let[G(zipmap"bdfhklgpqyitj""0000001111223")](apply str(flatten(interleave(for[v(re-seq #"\pL+"%)w[(rest(butlast v))]W[(into{}(for[[k v](group-by G w)][k(shuffle v)]))]R[(rest(reductions(fn[r i](merge-with + r{(G i)1})){}w))]][(first v)(map(fn[c r](nth(W(G c))(-(r(G c))1)))w R)(if(second v)(last v))])(re-seq #"\PL+"%)))))

I'm looking forward to seeing something shorter. Earlier ungolfed version with a few example runs:

(def f #(let[G(zipmap"bdfhklgpqyitj""0000001111223")] ; Create groups, the longest "acemnorsuvwxz" goes to an implicit group nil
          (apply str(flatten(interleave
                              (for[v (re-seq #"\w+"%)                                          ; Iterate over words
                                   w [(rest(butlast v))]                                       ; This holds the middle part
                                   W [(into{}(map(fn[[k v]][k(shuffle v)])(group-by G w)))]    ; Create shuffled groups
                                   R [(rest(reductions(fn[r i](merge-with + r{(G i)1})){}w))]] ; Calculate cumulative sum of group items, used to look-up nth value from shuffled values
                               [(first v)                                     ; First character
                                (map(fn[g r](nth(W g)(-(r g)1)))(map G w)R)   ; Shuffled middle part
                                (if(>(count v)1)(last v))])                   ; Last character, unless the word is just a single character
                              (re-seq #"\W+"%)))))) ; Interleave with spaces, commas, newline etc.

(f "It is well known that a text can still be read while the innards of its words have been scrambled, as long as their first and last letters plus their overall outlines remain constant.\n")
;  "It is well known that a txet can sitll be read wlihe the irnands of its wrods hvae been seacmlbrd, as lnog as their fisrt and lsat letters plus their oavrell ontlieus rmaein cnontast.\n"
;  "It is well kwonn that a text can sitll be raed wlihe the innards of its wrods hvae been seramlbcd, as long as their fisrt and lsat lettres plus their oravell ouiltnes rmeain cnsatont.\n"
;  "It is well konwn that a text can still be read while the iarnnds of its words have been sraemlbcd, as lnog as their first and lsat lrttees plus their oaevrll ontlieus remain canntsot.\n"
\$\endgroup\$
  • \$\begingroup\$ I think you need \pL+ and \PL+ rather than \w+ and \W+ to exclude digits and underscore. \$\endgroup\$ – Adám May 11 '17 at 7:18
0
\$\begingroup\$

Perl 6, 241 195 bytes

Includes +1 byte for -p command-line switch.

s:g/(<:L>)(<:L>+)(<:L>)/{$0}{[~]
$1.comb.pairs.classify({first
.value~~*,:k,/<[bdfhkl]>/,/<[gpqy]>/,/<[it]>/,/j/,!0}).values.map({$_».key
»=>«$_».value.pick(*)})».List.flat.sort».value}$2/;

Ungolfed:

s:g/(<:L>)(<:L>+)(<:L>)/{$0}{
    [~]
    $1.comb
    .pairs
    .classify({
        first .value ~~ *, :k,
            /<[bdfhkl]>/,
            /<[gpqy]>/,
            /<[it]>/,
            /j/,
            !0
    })
    .values
    .map({ $_».key »=>« $_».value.pick(*) })
    ».List
    .flat
    .sort
    ».value
}$2/;
\$\endgroup\$
  • \$\begingroup\$ I think you need (\pL)(\pL+)(\pL) rather than (\w)(\w+)(\w) to exclude digits and underscore. \$\endgroup\$ – Adám May 11 '17 at 7:19
  • \$\begingroup\$ Actually \pL includes a lot of characters outside of the allowed range of latin letters A-Z. I've updated my code to reflect the requirements more accurately. \$\endgroup\$ – Sean May 11 '17 at 21:34
  • \$\begingroup\$ Which characters? Remember that input is restricted to printable ASCII+Newlines. \$\endgroup\$ – Adám May 12 '17 at 3:18
  • \$\begingroup\$ Ah, I missed that. \pL is spelled <:L> in Perl 6 though. \$\endgroup\$ – Sean May 12 '17 at 5:42
0
\$\begingroup\$

C#, 438 394 380 374 bytes

namespace System.Text.RegularExpressions{using Linq;s=>Regex.Replace(s,@"\p{L}(([gpqy])|(i|t)|(j)|([bdf-l])|([a-z]))*?[a-z]?\b",m=>{var a=m.Value.ToArray();for(int i=1,j;++i<7;){var c=m.Groups[i].Captures;var n=c.Cast<Capture>().Select(p=>p.Index-m.Index).ToList();foreach(Capture p in c){a[j=n[new Random().Next(n.Count)]]=p.Value[0];n.Remove(j);}}return new string(a);});}

Save 10 bytes thanks to @MartinEnder♦.

Annoyingly, CaptureCollection doesn't implement IEnumerable<T> and that's why the .Cast<Capture>() is needed. Hopefully, I can combine the Linq query and the foreach loop though.

I'm sure there's a lot that can be golfed but it took me long enough just to get it working...

Try it online!

Formatted/Full version:

namespace System.Text.RegularExpressions
{
    using Linq;

    class P
    {
        static void Main()
        {
            Func<string, string> f = s =>
                Regex.Replace(s, @"\p{L}(([gpqy])|(i|t)|(j)|([bdf-l])|([a-z]))*?[a-z]?\b", m =>
                {
                    var a = m.Value.ToArray();

                    for (int i = 1, j; ++i < 7;)
                    {
                        var c = m.Groups[i].Captures;

                        var n = c.Cast<Capture>().Select(p => p.Index - m.Index).ToList();

                        foreach(Capture p in c)
                        {
                            a[j = n[new Random().Next(n.Count)]] = p.Value[0];
                            n.Remove(j);
                        }
                    }

                    return new string(a);
                });

            Console.WriteLine(f("Scramble words while preserving their outlines"));
            Console.ReadLine();
        }
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.