0

This problem is from the book Data Structure and Algorithms Made Easy by Narasimha Karumanchi chapter Recursion and Backtracking. The algorithm which is given in the book is as follows:

Let us assume we keep current k-ary string in an array A[0...n-1]. Call function k-string(n, k)

void k-string(int n, int k) {
  // process all k-ary strings of length m
  if(n < 1)
    printf("%s", A);       // Assume array A is a global variable
  else {
    for(int j=0; j<k; j++){
        A[n-1] = j;
        k-string(n-1, k);
    }
  } 
}

I couldn't understand the algorithm. Like why did they assigned an integer j to a string element?

  • I guess it's meant to illustrate the concept, not as working code. `A` is the string here, but not a character string, obviously, so `printf("%s"...` would not work. – 500 - Internal Server Error May 11 '20 at 09:36
  • Yeah, I understand that it's a pseudo-code but I didn't understand `A[n-1] = j`. Why they did that? – Soumya Sharma May 11 '20 at 10:41
  • That assignment is what builds the content of the string. Try stepping though e.g. with n==1 and k==3, or something. – 500 - Internal Server Error May 11 '20 at 11:27
  • But j is an integer and it is going into a char array. How that will give a string in the final answer? – Soumya Sharma May 11 '20 at 11:37
  • Right. That was the point of my previous comment: `A` is likely not a char array here but an array of int to make this assignment work. -- You could change A to `char[]` and then do something like `A[n-1] = (char) (j + 65);`, or whatever, to generate characters in the printable range, which would allow the `printf` to succeed. – 500 - Internal Server Error May 11 '20 at 11:42

1 Answers1

2
package main

import "fmt"

func printResult(A []int, n int) {
    var i int
    for ; i < n; i++ {
        // Function to print the output
        fmt.Print(A[i])
    }
    fmt.Printf("\n")
}

// Function to generate all k-ary strings
func generateK_aryStrings(n int, A []int, i int, k int) {
    if i == n {
        printResult(A, n)
        return
    }
    for j := 0; j < k; j++ {
        // assign j at ith position and try for all other permutations for remaining positions
        A[i] = j
        generateK_aryStrings(n, A, i+1, k)
    }
}

func main() {
    var n int = 4
    A := make([]int, n)

    // Print all binary strings
    generateK_aryStrings(n, A, 0, 3)
    return
}