2. Define a recursive function in the manner (defun permute (input-list) ...) wh
ID: 3745051 • Letter: 2
Question
2. Define a recursive function in the manner (defun permute (input-list) ...) which outputs a list of all permutations of a (short 'input-list' , without duplications. If 'input-list' is not a proper list, return it unchanged. IF THERE ARE MORE THAN 5 ELEMENTS IN THE INPUT-LIST, PRINT OUT AN ERROR MESSAGE, and return the input unchanged. Examples: (permute 'a) --> A (permute '(a . b) (A . B) (permute "( )) ==> (()) {a *list* containing the only permutation} (permute "(a b c)) ==> ((a b c) (a c b) (b a c) (c a b) (b c a) (c b a)) (permute (ab a)) ((a b a) (a a b) (ba a)) (permute '((a b) (c d) (a b)) -> ((a b) (c d) (a b)) ((a b) (a b) (c d)) ((c d) (a b) (a b))) (permute (a b c d e f)) ==> * ERROR: The input to 'permute' must not have more than 5 elements! (ABCDE F) N.B: Do NOT TRY TO ACTUALLY PERMUTE MORE THAN 5 ELEMENTS!! WE D0 NOT WISH TO BURN UP COMPUTER CYCLES AND MEMORY FOR NO GO0D REASON! NOTE: You can use the Common Lisp function 'remove-duplicates', but do it in the manner (remove-duplicates my-list :test equal otherwise things like (a b), (a b) will be deemed unequal! Common Lisp distinguishes, eq, eql, and equal. Read up on how these differ; e.g., (equal '(a b) '(a b))> T, whereas (eq "(a b) (a b)) ==> NILExplanation / Answer
#include <bits/stdc++.h>
using namespace std;
bool shouldSwap(char str[], int start, int curr)
{
for (int i = start; i < curr; i++)
if (str[i] == str[curr])
return 0;
return 1;
}
void findPermutations(char str[], int index, int n)
{
if(strlen(str)>5)
return;
if (index >= n) {
cout <<"("<< str << ") ";
return;
}
for (int i = index; i < n; i++) {
bool check = shouldSwap(str, index, i);
if (check) {
swap(str[index], str[i]);
findPermutations(str, index + 1, n);
swap(str[index], str[i]);
}
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.