Jump to content

Bash syntax


Richard_Grant

Recommended Posts

This is a simple permutation function that i was converting from php:

string_gen(){
    declare -a chars=('a' 'b')
    max=4
    let length=${#chars[@]}-1
    n=0
    combination=" "
    for i in `seq 0 $max`;
    do
        let n=($n*($length))+($length)
    done 
    remainder=0
    for i in `seq 0 $n`;
    do
        current=$i
        combination=" "
        while [[ $current > 0 ]]
        do
           remainder=($current%$length)
           echo remainder
           if [ $remainder -eq 0 ]; then
                combination="$combination"${chars[$length]}
            else
                combination="$combination"${chars[$remainder]}
                current = $current/$length
           fi
        done
    done 
    echo $combination
}

What is wrong with the syntax?

 

Link to PHP version: http://stackoverflow.com/questions/12293870/algorithm-to-get-all-possible-string-combinations-from-array-up-to-certain-lengt

Link to comment
Share on other sites

Following the logic of your script, I modified it a little and got 4 bbbb's. 

 

Here it is,

 

freaks_bash

#!/bin/bash

string_gen(){

    declare -a chars=('a' 'b')

    remainder=0
    current=1
    combination=" "
    max=4
    n=0

   let length=${#chars[@]}-1

    for i in `seq 0 $max`;
    do
       let n=$n*$length+$length
    done 
    
while [[ $n -gt $current ]]; do
      
       remainder=$current%$length
      
      if [[ $remainder -eq 0 ]]; then
                combination="$combination"${chars[$length]}
            else
                combination="$combination"${chars[$remainder]}

                current = $current/$length
           fi

let current=current+1

done

echo $combination;
}

string_gen # call the function

Result:

[lxc@lxc-box ~]$ ./freaks_bash 
bbbb

What result are you expecting to get?

Edited by jazzman1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.