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
https://forums.phpfreaks.com/topic/291263-bash-syntax/
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?

Link to comment
https://forums.phpfreaks.com/topic/291263-bash-syntax/#findComment-1492009
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.