![]() |
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.
|
|
google unix.com
|
|||||||
| Forums | Register | Forum Rules | Links | Albums | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
| Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts and shell scripting languages here. |
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Search, replace string in file1 with string from (lookup table) file2? | gstuart | Shell Programming and Scripting | 9 | 06-08-2009 06:11 AM |
| libapache2-mod-scramble-ip 0.2 (Default branch) | iBot | Software Releases - RSS News | 0 | 07-10-2008 06:50 PM |
| Scramble Eggs 1.1 (Default branch) | iBot | Software Releases - RSS News | 0 | 05-04-2008 05:30 PM |
| appending string to text file based on search string | malaymaru | Shell Programming and Scripting | 1 | 06-09-2006 08:53 AM |
| sed problem - replacement string should be same length as matching string. | amangeles | Shell Programming and Scripting | 4 | 01-11-2006 06:11 AM |
![]() |
|
|
LinkBack | Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
||||
|
Scramble a string.
Hi all,
I am trying to write a perl script that will take user input as a string and scramble the string and print the result. Note: I cannot use shuffle function ....using for loop. Code:
so here is example. Enter a String: abcdef Print the Result: debacf Enter a String: abcdef print the Result: cdabef Code:
print "Enter a string: ";
$sString = <STDIN>;
chomp($sString);
print "String = $sString\n";
$iLength = length($sString);
@array = split(//, $sString);
print "array = @array\n";
print "length = $iLength\n";
for ( $i = 1; $i <= $iLength; $i++ ){
$item = int(rand($#array));
print "@array[$item]\n";
}
thanks, |
|
||||
|
The simplest way is to loop through the array swapping each item with another item in a random position. Note that the array is indexed from 0, not 1.
Code:
for ( $i = 0; $i < $iLength; $i++ ){
$random = int(rand($#array));
$temp=$array[$random];
$array[$random]=$array[$i];
$array[$i]=$temp;
}
for ( $i = 0; $i < $iLength; $i++ ){
print "$array[$i]";
}
print "\n";
|
|
||||
|
|
| Sponsored Links | ||
|
|