1

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
4
  • 1
    Where do you set $2? Commented May 5, 2019 at 11:50
  • You re-initialize the global array variable every time you enter the function. Move array=() outside of the function. Commented May 5, 2019 at 13:24
  • @cyrus, in the recursive permutation call within the function. Commented May 5, 2019 at 13:25
  • I moved array=() out and still nothing Commented May 5, 2019 at 16:04

1 Answer 1

1
  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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.