Permutations for strings (code)
3 posters
Page 1 of 1
Permutations for strings (code)
- Code:
#include <iostream>
#include<string.h>
#include<stdlib.h>
#include<sys/time.h>
using namespace std;
void Permutations(char*,int,int);
int fact=1,a[60000]={},count=0;
int main()
{
char str[50];
int i,l;
cout<<"Enter the string: ";
cin>>str;
l=strlen(str);
for(i=2;i<=l;i++)
{
fact=fact*i;
}
Permutations(str,0,(l--));
cout<<"\n\n\n\n";
return 0;
}
void Permutations(char* str,int i,int l)
{
if (i == l)
{
long int m=atol(str);
if(a[m]==0)
{
a[m]=1;
count++;
cout<<count<<") "<<str<<endl;
}
}
else
{
for(int j= i;j<l;j++ )
{
char temp=str[i];
str[i]=str[j];
str[j]=temp;
long int m=atol(str);
if(a[m]==0)
{
a[m]=1;
count++;
cout<<count<<") "<<str<<endl;
}
Permutations(str, i + 1,l);
temp=str[i];
str[i]=str[j];
str[j]=temp;
m=atol(str);
if(a[m]==0)
{
a[m]=1;
count++;
cout<<count<<") "<<str<<endl;
}
}
}
return;
}
Last edited by Anup Atluri on Wed Aug 24, 2011 12:11 am; edited 3 times in total
Anup Atluri- Posts : 5
Points : 10
Reputation : 0
Join date : 2011-08-14
Re: Permutations for strings (code)
works for string of length 5.. i.e. 120 possiblities.. for 6 i get segmentation fault..
Re: Permutations for strings (code)
prashanthjbabu wrote:works for string of length 5.. i.e. 120 possiblities.. for 6 i get segmentation fault..
increase the array size
Anup Atluri- Posts : 5
Points : 10
Reputation : 0
Join date : 2011-08-14
Re: Permutations for strings (code)
works great .. we used a brute force method.. used rand function to generate possibilties..
Re: Permutations for strings (code)
there seems to be some issue with strings.. when i type integers like 1234567 it works fine..but for "abcd" it doesnt..
Re: Permutations for strings (code)
prashanthjbabu wrote:there seems to be some issue with strings.. when i type integers like 1234567 it works fine..but for "abcd" it doesnt..
use strtol(str,&end,16); instead of atol();
(define char *end=0; before using &end)
Anup Atluri- Posts : 5
Points : 10
Reputation : 0
Join date : 2011-08-14
Re: Permutations for strings (code)
Anup, from next time on, use the code option provided. It retains the indentation of the program code. That was one of the main reasons for porting the group out to here :-)
thoshi11- Posts : 4
Points : 6
Reputation : -2
Join date : 2011-08-17
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum