0

Does somebody know what is wrong and why it doesn't want to add all permutations in function into an array "array" and when I run for loop only gives me last value

#!/bin/bash
array=()
permutation() {

  local items="$1"
  local out="$2"
  local i
  [[ "$items" == "" ]] && array[$i]="$out" && return
  for (( i=0; i<${#items}; i++ )) ; do
    permutation "${items:0:i}${items:i+1}" "$out${items:i:1}"
  done
  }

permutation $1

for i in "${array[$i]}"
do 
  echo "$i"
done
rndint
  • 11
  • 2

1 Answers1

0
  1. Use array+=( "$out" ) to append to the end of your array without needing to know the index of that value. Because you're declaring i local, it isn't shared across the invocations of your functions, so they're all overwriting ${array[0]}.
  2. for i in "${array[$i]}"; do ignores all the values of your array except for whichever one is in position $i, for the single value of i that exists before your for loop is entered. Use for i in "${array[@]}" to iterate over all values in the array.

See a corrected version of your code running at https://ideone.com/zIYigA

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441