Full Permutation Algorithm in BASH
Swap Two Characters in BASH
In BASH, we can use "${#string}" to get the length of a string. And in a function, we use "local" keyword to declare local variables. And strings are immuntable in BASH, and thus we can use the following function to swap two characters in a string:
function swap() {
local string=$1
local len=${#string}
local from=$2
local to=$3
local i=0
local s=""
while [[ $i -lt $len ]]; do
if [[ $i -eq $from ]]; then
s=$s${string:$to:1}
elif [[ $i -eq $to ]]; then
s=$s${string:$from:1}
else
s=$s${string:$i:1}
fi
i=$(($i+1))
done
echo $s
}
Full Permutation Algorithm in BASH
And then, with the perm function, we can recursively "swap" two letters and get the full permutation:
#!/bin/bash
function swap() {
local string=$1
local len=${#string}
local from=$2
local to=$3
local i=0
local s=""
while [[ $i -lt $len ]]; do
if [[ $i -eq $from ]]; then
s=$s${string:$to:1}
elif [[ $i -eq $to ]]; then
s=$s${string:$from:1}
else
s=$s${string:$i:1}
fi
i=$(($i+1))
done
echo $s
}
function perm() {
local string=$1
local len=${#string}
local idx=$2
if [[ $idx -ge $len ]]; then
echo $string
else
local i=$idx
while [[ $i -lt $len ]]; do
perm $(swap $string $i $idx) $((idx+1))
i=$((i+1))
done
fi
}
perm $1
# ./perm.sh 123
123
132
213
231
321
312
Full Permutation Algorithms:
- A Recursive Full Permutation Algorithm in Python
- Teaching Kids Programming – Recursive Permutation Algorithm
- The Permutation Iterator in Python
- GoLang: Full Permutation Command Line Tool
- Teaching Kids Programming - Introduction to Permutation and Combination
- The Permutation Algorithm for Arrays using Recursion
- Full Permutation Algorithm Implementation in BASH
Reposted to Blog
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^
NEW! Following my Trail (Upvote or/and Downvote)
Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com
My contributions
- Video Downloader
- Steem Blockchain Tools
- Free Cryptos API
- VPS Database
- Computing Technology Blog
- A few useless tools
- And some other online software/tools
- Merge Files/Videos
- LOGO Turtle Programming Chrome Extension
- Teaching Kids Programming - Youtube Channel and All Contents
Delegation Service
Important Update of Delegation Service!
Support me
If you like my work, please:
- Buy Me a Coffee, Thanks!
- Become my Sponsor, Thanks!
- Voting for me:
https://steemit.com/~witnesses type in justyy and click VOTE
- Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
- Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
- Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses
this one looking hard.
well.. it did take me a while to figure out the correct syntax for BASH. :P