473,799 Members | 3,081 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

function to permute a string

hello all, not sure if it's appropriate to post here. If not, I am sorry
and please direct me to the right groups. Thanks.
I write this function to permute a string. e.g. if the input string is
"abc", I am expecting to see the output: "abc", "acb", "bac", "bca",
"cab", "cba"
there is n! output for a string of size(n). Here is my code fragment,
Can anyone points out how to improve my code so that I get the right
output. You can see the current input for just running the code. I believe
the algorithm is correct. Thanks.
void permute(char *s)
{
int i,j,k;
char str[100];

if (strlen(s) <= 1)
printf("%s\n", s);
else {
for (i=0; i< strlen(s); i++) {
memset(str, 0, sizeof(str));
printf("%c",s[i]);
strcpy(str,s);
for (j=i; j<strlen(s); j++)
str[j] = str[j+1];

str[strlen(s)-1] = 0;
permute(str);
}
}
}
Nov 14 '05 #1
2 4678
On 4 Aug 2004 15:15:50 GMT, Yuan Zhong <yz****@henri.m ath.fsu.edu>
wrote:
hello all, not sure if it's appropriate to post here. If not, I am sorry
and please direct me to the right groups. Thanks.
I write this function to permute a string. e.g. if the input string is
"abc", I am expecting to see the output: "abc", "acb", "bac", "bca",
"cab", "cba"
there is n! output for a string of size(n). Here is my code fragment,
Can anyone points out how to improve my code so that I get the right
output. You can see the current input for just running the code. I believe
the algorithm is correct. Thanks.
void permute(char *s)


I would implement this by passing two arguments. To start call

permute( "", "abc" );

This recusively makes the following calls:

permute( "a", "bc" );
permute( "b", "ac" );
permute( "c", "ab" );

Each call permute() takes one character from the second string
and appends it to the first string.

permute( "a", "bc" ) will call:
permute( "ab", "c" )
permute( "ac", "b" )

permute( "b", "ac" ) will call:
permute( "ba", "c" )
permute( "bc", "a" )

permute( "c", "ab" ) will call:
permute( "ca", "b" )
permute( "cb", "a" )

Nick.
Nov 14 '05 #2
Yuan Zhong wrote:
.... snip ...
I write this function to permute a string. e.g. if the input
string is "abc", I am expecting to see the output: "abc", "acb",
"bac", "bca", "cab", "cba" there is n! output for a string of
size(n). Here is my code fragment, Can anyone points out how to
improve my code so that I get the right output. ...

.... snip code ...

I didn't attempt to check your code. Here is a version I have
used for some time:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* Public domain, by C.B. Falconer. Attribution appreciated. */

/* Things get out of hand when larger than 8 */
#define MAXWORD 12

/* ------------------ */

/* exchange 0th and ith char in wd */
void trade(char *wd, unsigned int i)
{
char c;

c = *wd;
*wd = wd[i];
wd[i] = c;
} /* trade */

/* ------------------ */

/* Form all n char permutations of the characters in the
string wd of length lgh into outstring at index ix.
Output the results to stdout. */
void jumble(char *wd, unsigned int lgh,
unsigned int ix, /* output place to fill */
unsigned int n, /* max out places to fill */
char *outstring)
{
unsigned int i;

if (0 == n) {
outstring[ix] = '\0';
puts(outstring) ;
}
else
for (i = 0; i < lgh; i++) {
trade(wd, i); /* nop when (0 == i) */
outstring[ix] = *wd;
jumble(wd+1, lgh-1, ix+1, n-1, outstring);
trade(wd, i); /* restore the wd string */
}
} /* jumble */

/* ------------------ */

int main(int argc, char *argv[])
{
unsigned int n, lgh, min;
double max;
char outstring[MAXWORD];

if (argc < 2) {
fprintf(stderr,
"Usage: jumble <baseword> [lgh]\n"
" where the (optional) lgh specifies the\n"
" maximum length of the output words\n");
return 0;
}
lgh = strlen(argv[1]);
if (lgh >= MAXWORD) argv[1][lgh = MAXWORD-1] = '\0';

min = lgh;
if ((argc > 2) && (1 == sscanf(argv[2], "%u", &n)))
if (n && (n <= lgh)) min = n;

for (n = lgh, max = 1.0; n > (lgh - min); n--)
max = max * n;

fprintf(stderr, "string=\"% s\", max=%.0f, len=%u\n",
argv[1], max, min);

jumble(argv[1], lgh, 0, min, outstring);
return 0;
} /* main */

--
"I'm a war president. I make decisions here in the Oval Office
in foreign policy matters with war on my mind." - Bush.
"Churchill and Bush can both be considered wartime leaders, just
as Secretariat and Mr Ed were both horses." - James Rhodes.
"If I knew then what I know today, I would still have invaded
Iraq. It was the right decision" - G.W. Bush, 2004-08-02
Nov 14 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
5683
by: Steve Goldman | last post by:
Hi, I am trying to come up with a way to develop all n-length permutations of a given list of values. The short function below seems to work, but I can't help thinking there's a better way. Not being a computer scientist, I find recursive functions to be frightening and unnatural. I'd appreciate if anyone can tell me the pythonic idiom to accomplish this. Thanks for your help,
9
3699
by: Derek Hart | last post by:
I wish to execute code from a string. The string will have a function name, which will return a string: Dim a as string a = "MyFunctionName(param1, param2)" I have seen a ton of people discuss how reflection does this, but I cannot find the syntax to do this. I have tried several code example off of gotdotnet and other articles. Can somebody please show me the code to do this?
3
14955
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
3
1522
by: Richard A. DeVenezia | last post by:
Can a function write another function that has a specific number of nested loops and then run it? i.e. function maker (N) { // does stuff that creates function doer() // invoke doer doer() }
7
15186
by: Sriram Rajagopalan | last post by:
Hi, Can ne 1 give me the logic of permuting a string in C language. What I meant is that suppose if u have a string like "man" the output should b: man mna
1
2268
by: candexis | last post by:
So I am working with classes and I have the following Method, which rotate a variable: unsigned __int64 Subkeys::RotaionalLeftShift() { unsigned __int64 top_bits = 0; top_bits = K >> (sizeof K * CHAR_BIT) -desplazar; K <<= desplazar; K |= top_bits;
1
1656
by: Schüle Daniel | last post by:
Hello, I came up with this algorithm to generate all permutations it's not the best one, but it's easy enough # lst = list with objects def permute3(lst): tmp = lenlst = len(lst) def permute(perm, level):
28
4340
by: Larax | last post by:
Best explanation of my question will be an example, look below at this simple function: function SetEventHandler(element) { // some operations on element element.onclick = function(event) {
2
3005
by: peace357 | last post by:
I am trying to write two recursive functions involving two strings, 1)CAT & 2)MAN. My function needs to print out: TACMAN ATCMAN CTAMAN TCAMAN ACTMAN CATMAN
0
9540
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10475
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10222
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10026
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9068
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5463
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.