Does this shuffle have non-zero probability for all permutations?Rechecking contiguous characters (as in run length encoding)Find Length of longest substring with all 1's in a binary string with k queriesMinimal set of rows and columns covering all non-zero entries in matrixHow to write decoder for compressed stringified objectsAlgorithm for this problem on generating all permutationsDoes this “reference” problem have a name?Algorithm To Process Purchases Efficiently and Apply ConstraintCalculate probabilty to escape the maze

Why is CMYK & PNG not possible?

Fill a bowl with alphabet soup

Does Australia produce unique 'specialty steel'?

Why are Starfleet vessels designed with nacelles so far away from the hull?

Delete line if next line is the same

How can my hammerspace safely "decompress"?

Can Slack really claim not to be a data controller?

Could someone please translate this code into some mathematical notation?

Can you take Bowwow out after returning him to MeowMeow?

SSD or HDD for server

A Grandma Riddle

How to deal with intolerable behavior of a subordinate?

C4_4 Reflection!

Print the sequence

How should I tell a professor the answer to something he doesn't know?

Future of iTunes and audio files in its library

How do I make the same variable available to all my theme files?

An idiomatic word for "very little" in this context?

What causes standard door hinges to close up to a certain amount automatically?

How did Ron get five hundred Chocolate Frog cards?

Is It Possible to Make a Computer Virus That Acts as an Anti-virus?

String Operation to Split on Punctuation

If the music alphabet had more than 7 letters would octaves still sound like the same note?

Get first and last day of the week in Ampscript



Does this shuffle have non-zero probability for all permutations?


Rechecking contiguous characters (as in run length encoding)Find Length of longest substring with all 1's in a binary string with k queriesMinimal set of rows and columns covering all non-zero entries in matrixHow to write decoder for compressed stringified objectsAlgorithm for this problem on generating all permutationsDoes this “reference” problem have a name?Algorithm To Process Purchases Efficiently and Apply ConstraintCalculate probabilty to escape the maze






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









2














$begingroup$


I was trying to do some code golf, when I created the following algorithm to shuffle a string:



for(;k-->0;y=s,s="")for(var c:y.split(""))s=Math.random()<.5?s+c:c+s;


To explain better what it does, I've recreated it in Python:



import random
str = "Randomize me!"
print('[',str,']',sep='')
temp=""
for _ in range(len(str)): # repeat as many times as the string is long
for char in str: # take the string's chars and randomly construct a temporary
temp = temp + char if random.choice([True, False]) else char + temp
temp, str = "", temp # use the temporary as the basis for the next iteration
print('[',str,']',sep='')


Also, per request, here it is in pseudocode:



SHUFFLE(STR)
0 TEMP ← ""
1 LOOP STR.LENGTH TIMES:
2 FOR EACH CHAR ∈ STR:
3 IF COIN-FLIP
4 TEMP = TEMP + CHAR
5 ELSE
6 TEMP = CHAR + TEMP
7 END IF
8 STR ← TEMP
9 TEMP ← ""
10 END FOR
11 END LOOP
12 RETURN STR


The output looks randomized to me. However, if you only consider one iteration of the algorithm, the first character put into temp is always str[0]. The second character put into temp on this iteration is always str[1], which must be next to str[0] according to the way characters are appended. Therefore, after one iteration, the probability that the shuffled string has the first character outside of the center is 0, and the probability that it is not adjacent to the second character is 0.

I tried to remedy this problem by repeating the shuffle once for each character in the string. Intuitively, it seems to work, but I can't seem to prove that all permutations of the input string can show up.



So, here's the question: do all permutations of the input string have non-zero probability as output from this shuffle?










share|cite









New contributor



Avi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$











  • 1




    $begingroup$
    @DavidRicherby No problem. Is there a standard format for pseudocode?
    $endgroup$
    – Avi
    2 hours ago










  • $begingroup$
    @DavidRicherby Done :)
    $endgroup$
    – Avi
    2 hours ago










  • $begingroup$
    Thanks -- that's great!
    $endgroup$
    – David Richerby
    52 mins ago

















2














$begingroup$


I was trying to do some code golf, when I created the following algorithm to shuffle a string:



for(;k-->0;y=s,s="")for(var c:y.split(""))s=Math.random()<.5?s+c:c+s;


To explain better what it does, I've recreated it in Python:



import random
str = "Randomize me!"
print('[',str,']',sep='')
temp=""
for _ in range(len(str)): # repeat as many times as the string is long
for char in str: # take the string's chars and randomly construct a temporary
temp = temp + char if random.choice([True, False]) else char + temp
temp, str = "", temp # use the temporary as the basis for the next iteration
print('[',str,']',sep='')


Also, per request, here it is in pseudocode:



SHUFFLE(STR)
0 TEMP ← ""
1 LOOP STR.LENGTH TIMES:
2 FOR EACH CHAR ∈ STR:
3 IF COIN-FLIP
4 TEMP = TEMP + CHAR
5 ELSE
6 TEMP = CHAR + TEMP
7 END IF
8 STR ← TEMP
9 TEMP ← ""
10 END FOR
11 END LOOP
12 RETURN STR


The output looks randomized to me. However, if you only consider one iteration of the algorithm, the first character put into temp is always str[0]. The second character put into temp on this iteration is always str[1], which must be next to str[0] according to the way characters are appended. Therefore, after one iteration, the probability that the shuffled string has the first character outside of the center is 0, and the probability that it is not adjacent to the second character is 0.

I tried to remedy this problem by repeating the shuffle once for each character in the string. Intuitively, it seems to work, but I can't seem to prove that all permutations of the input string can show up.



So, here's the question: do all permutations of the input string have non-zero probability as output from this shuffle?










share|cite









New contributor



Avi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$











  • 1




    $begingroup$
    @DavidRicherby No problem. Is there a standard format for pseudocode?
    $endgroup$
    – Avi
    2 hours ago










  • $begingroup$
    @DavidRicherby Done :)
    $endgroup$
    – Avi
    2 hours ago










  • $begingroup$
    Thanks -- that's great!
    $endgroup$
    – David Richerby
    52 mins ago













2












2








2





$begingroup$


I was trying to do some code golf, when I created the following algorithm to shuffle a string:



for(;k-->0;y=s,s="")for(var c:y.split(""))s=Math.random()<.5?s+c:c+s;


To explain better what it does, I've recreated it in Python:



import random
str = "Randomize me!"
print('[',str,']',sep='')
temp=""
for _ in range(len(str)): # repeat as many times as the string is long
for char in str: # take the string's chars and randomly construct a temporary
temp = temp + char if random.choice([True, False]) else char + temp
temp, str = "", temp # use the temporary as the basis for the next iteration
print('[',str,']',sep='')


Also, per request, here it is in pseudocode:



SHUFFLE(STR)
0 TEMP ← ""
1 LOOP STR.LENGTH TIMES:
2 FOR EACH CHAR ∈ STR:
3 IF COIN-FLIP
4 TEMP = TEMP + CHAR
5 ELSE
6 TEMP = CHAR + TEMP
7 END IF
8 STR ← TEMP
9 TEMP ← ""
10 END FOR
11 END LOOP
12 RETURN STR


The output looks randomized to me. However, if you only consider one iteration of the algorithm, the first character put into temp is always str[0]. The second character put into temp on this iteration is always str[1], which must be next to str[0] according to the way characters are appended. Therefore, after one iteration, the probability that the shuffled string has the first character outside of the center is 0, and the probability that it is not adjacent to the second character is 0.

I tried to remedy this problem by repeating the shuffle once for each character in the string. Intuitively, it seems to work, but I can't seem to prove that all permutations of the input string can show up.



So, here's the question: do all permutations of the input string have non-zero probability as output from this shuffle?










share|cite









New contributor



Avi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$




I was trying to do some code golf, when I created the following algorithm to shuffle a string:



for(;k-->0;y=s,s="")for(var c:y.split(""))s=Math.random()<.5?s+c:c+s;


To explain better what it does, I've recreated it in Python:



import random
str = "Randomize me!"
print('[',str,']',sep='')
temp=""
for _ in range(len(str)): # repeat as many times as the string is long
for char in str: # take the string's chars and randomly construct a temporary
temp = temp + char if random.choice([True, False]) else char + temp
temp, str = "", temp # use the temporary as the basis for the next iteration
print('[',str,']',sep='')


Also, per request, here it is in pseudocode:



SHUFFLE(STR)
0 TEMP ← ""
1 LOOP STR.LENGTH TIMES:
2 FOR EACH CHAR ∈ STR:
3 IF COIN-FLIP
4 TEMP = TEMP + CHAR
5 ELSE
6 TEMP = CHAR + TEMP
7 END IF
8 STR ← TEMP
9 TEMP ← ""
10 END FOR
11 END LOOP
12 RETURN STR


The output looks randomized to me. However, if you only consider one iteration of the algorithm, the first character put into temp is always str[0]. The second character put into temp on this iteration is always str[1], which must be next to str[0] according to the way characters are appended. Therefore, after one iteration, the probability that the shuffled string has the first character outside of the center is 0, and the probability that it is not adjacent to the second character is 0.

I tried to remedy this problem by repeating the shuffle once for each character in the string. Intuitively, it seems to work, but I can't seem to prove that all permutations of the input string can show up.



So, here's the question: do all permutations of the input string have non-zero probability as output from this shuffle?







algorithms strings probability-theory randomized-algorithms






share|cite









New contributor



Avi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










share|cite









New contributor



Avi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








share|cite




share|cite



share|cite








edited 2 hours ago







Avi













New contributor



Avi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked 8 hours ago









AviAvi

1134 bronze badges




1134 bronze badges




New contributor



Avi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




Avi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • 1




    $begingroup$
    @DavidRicherby No problem. Is there a standard format for pseudocode?
    $endgroup$
    – Avi
    2 hours ago










  • $begingroup$
    @DavidRicherby Done :)
    $endgroup$
    – Avi
    2 hours ago










  • $begingroup$
    Thanks -- that's great!
    $endgroup$
    – David Richerby
    52 mins ago












  • 1




    $begingroup$
    @DavidRicherby No problem. Is there a standard format for pseudocode?
    $endgroup$
    – Avi
    2 hours ago










  • $begingroup$
    @DavidRicherby Done :)
    $endgroup$
    – Avi
    2 hours ago










  • $begingroup$
    Thanks -- that's great!
    $endgroup$
    – David Richerby
    52 mins ago







1




1




$begingroup$
@DavidRicherby No problem. Is there a standard format for pseudocode?
$endgroup$
– Avi
2 hours ago




$begingroup$
@DavidRicherby No problem. Is there a standard format for pseudocode?
$endgroup$
– Avi
2 hours ago












$begingroup$
@DavidRicherby Done :)
$endgroup$
– Avi
2 hours ago




$begingroup$
@DavidRicherby Done :)
$endgroup$
– Avi
2 hours ago












$begingroup$
Thanks -- that's great!
$endgroup$
– David Richerby
52 mins ago




$begingroup$
Thanks -- that's great!
$endgroup$
– David Richerby
52 mins ago










1 Answer
1






active

oldest

votes


















3
















$begingroup$

Yes. Your algorithm can return all permutations.
You can prove it by fixing any arbitrary permutation $pi$ of the input string str and showing by induction that, after the $i$-th iteration of the outer loop, the first $i$ characters of str can match the last $i$ characters of $pi$.



For $i=0$ this is trivial.
For $i>0$: Let $n$ be the lenght of str, $x$ be the character in position $1+n-i$ of $pi$ (indexing positions from $1$), and $j$ be the index of the first occurrence of character $x$ in str with the additional constraint that $j ge i$ (this index always exists by induction hypothesis). A string temp that will satisfy the induction thesis (as it will be assigned to str) can be found as follows:



  • copy the first $j-1$ characters from str to temp (by appending them to temp). In particular this copies the first $i-1$ characters of str which, by induction hypothesis, match the last $i-1$ characters of $pi$.

  • prepend the $j$-th character of $x$ of str to temp.

  • append the remaining $n-j$ characters of str to temp.





share|cite|improve this answer












$endgroup$














  • $begingroup$
    Seems like building the target permutation backwards by selecting one character at a time? Makes sense.
    $endgroup$
    – Avi
    7 hours ago











  • $begingroup$
    Yeah, that's exactly the idea.
    $endgroup$
    – Steven
    7 hours ago












Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "419"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);







Avi is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded
















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcs.stackexchange.com%2fquestions%2f115438%2fdoes-this-shuffle-have-non-zero-probability-for-all-permutations%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown


























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3
















$begingroup$

Yes. Your algorithm can return all permutations.
You can prove it by fixing any arbitrary permutation $pi$ of the input string str and showing by induction that, after the $i$-th iteration of the outer loop, the first $i$ characters of str can match the last $i$ characters of $pi$.



For $i=0$ this is trivial.
For $i>0$: Let $n$ be the lenght of str, $x$ be the character in position $1+n-i$ of $pi$ (indexing positions from $1$), and $j$ be the index of the first occurrence of character $x$ in str with the additional constraint that $j ge i$ (this index always exists by induction hypothesis). A string temp that will satisfy the induction thesis (as it will be assigned to str) can be found as follows:



  • copy the first $j-1$ characters from str to temp (by appending them to temp). In particular this copies the first $i-1$ characters of str which, by induction hypothesis, match the last $i-1$ characters of $pi$.

  • prepend the $j$-th character of $x$ of str to temp.

  • append the remaining $n-j$ characters of str to temp.





share|cite|improve this answer












$endgroup$














  • $begingroup$
    Seems like building the target permutation backwards by selecting one character at a time? Makes sense.
    $endgroup$
    – Avi
    7 hours ago











  • $begingroup$
    Yeah, that's exactly the idea.
    $endgroup$
    – Steven
    7 hours ago















3
















$begingroup$

Yes. Your algorithm can return all permutations.
You can prove it by fixing any arbitrary permutation $pi$ of the input string str and showing by induction that, after the $i$-th iteration of the outer loop, the first $i$ characters of str can match the last $i$ characters of $pi$.



For $i=0$ this is trivial.
For $i>0$: Let $n$ be the lenght of str, $x$ be the character in position $1+n-i$ of $pi$ (indexing positions from $1$), and $j$ be the index of the first occurrence of character $x$ in str with the additional constraint that $j ge i$ (this index always exists by induction hypothesis). A string temp that will satisfy the induction thesis (as it will be assigned to str) can be found as follows:



  • copy the first $j-1$ characters from str to temp (by appending them to temp). In particular this copies the first $i-1$ characters of str which, by induction hypothesis, match the last $i-1$ characters of $pi$.

  • prepend the $j$-th character of $x$ of str to temp.

  • append the remaining $n-j$ characters of str to temp.





share|cite|improve this answer












$endgroup$














  • $begingroup$
    Seems like building the target permutation backwards by selecting one character at a time? Makes sense.
    $endgroup$
    – Avi
    7 hours ago











  • $begingroup$
    Yeah, that's exactly the idea.
    $endgroup$
    – Steven
    7 hours ago













3














3










3







$begingroup$

Yes. Your algorithm can return all permutations.
You can prove it by fixing any arbitrary permutation $pi$ of the input string str and showing by induction that, after the $i$-th iteration of the outer loop, the first $i$ characters of str can match the last $i$ characters of $pi$.



For $i=0$ this is trivial.
For $i>0$: Let $n$ be the lenght of str, $x$ be the character in position $1+n-i$ of $pi$ (indexing positions from $1$), and $j$ be the index of the first occurrence of character $x$ in str with the additional constraint that $j ge i$ (this index always exists by induction hypothesis). A string temp that will satisfy the induction thesis (as it will be assigned to str) can be found as follows:



  • copy the first $j-1$ characters from str to temp (by appending them to temp). In particular this copies the first $i-1$ characters of str which, by induction hypothesis, match the last $i-1$ characters of $pi$.

  • prepend the $j$-th character of $x$ of str to temp.

  • append the remaining $n-j$ characters of str to temp.





share|cite|improve this answer












$endgroup$



Yes. Your algorithm can return all permutations.
You can prove it by fixing any arbitrary permutation $pi$ of the input string str and showing by induction that, after the $i$-th iteration of the outer loop, the first $i$ characters of str can match the last $i$ characters of $pi$.



For $i=0$ this is trivial.
For $i>0$: Let $n$ be the lenght of str, $x$ be the character in position $1+n-i$ of $pi$ (indexing positions from $1$), and $j$ be the index of the first occurrence of character $x$ in str with the additional constraint that $j ge i$ (this index always exists by induction hypothesis). A string temp that will satisfy the induction thesis (as it will be assigned to str) can be found as follows:



  • copy the first $j-1$ characters from str to temp (by appending them to temp). In particular this copies the first $i-1$ characters of str which, by induction hypothesis, match the last $i-1$ characters of $pi$.

  • prepend the $j$-th character of $x$ of str to temp.

  • append the remaining $n-j$ characters of str to temp.






share|cite|improve this answer















share|cite|improve this answer




share|cite|improve this answer



share|cite|improve this answer








edited 1 hour ago

























answered 8 hours ago









StevenSteven

1,1227 silver badges12 bronze badges




1,1227 silver badges12 bronze badges














  • $begingroup$
    Seems like building the target permutation backwards by selecting one character at a time? Makes sense.
    $endgroup$
    – Avi
    7 hours ago











  • $begingroup$
    Yeah, that's exactly the idea.
    $endgroup$
    – Steven
    7 hours ago
















  • $begingroup$
    Seems like building the target permutation backwards by selecting one character at a time? Makes sense.
    $endgroup$
    – Avi
    7 hours ago











  • $begingroup$
    Yeah, that's exactly the idea.
    $endgroup$
    – Steven
    7 hours ago















$begingroup$
Seems like building the target permutation backwards by selecting one character at a time? Makes sense.
$endgroup$
– Avi
7 hours ago





$begingroup$
Seems like building the target permutation backwards by selecting one character at a time? Makes sense.
$endgroup$
– Avi
7 hours ago













$begingroup$
Yeah, that's exactly the idea.
$endgroup$
– Steven
7 hours ago




$begingroup$
Yeah, that's exactly the idea.
$endgroup$
– Steven
7 hours ago











Avi is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded

















Avi is a new contributor. Be nice, and check out our Code of Conduct.












Avi is a new contributor. Be nice, and check out our Code of Conduct.











Avi is a new contributor. Be nice, and check out our Code of Conduct.














Thanks for contributing an answer to Computer Science Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcs.stackexchange.com%2fquestions%2f115438%2fdoes-this-shuffle-have-non-zero-probability-for-all-permutations%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown









Popular posts from this blog

Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480