I'm trying to find a efficient algorithm in C, which provides me all combinations of a given charset.
The algorithm should not recursive. At last the number of digits should be flexible. For example:
char set[] = "a1";
->
a1
aa
1a
11
I've only found a Perl solution, but it uses substr(). I think that wasn't that fast performance-wise.
For most algorithms in C, I've found were only permutations...
A article in a german C++ forum claims, that C++-STL Solutions are faster than "raw" recursive algorithms.
If the set size were a fixed N it would be simple - you could just have N for loops, each one nested into the previous one. Since you can't do this and you can't use recursion, you have to calculate the total required number of iterations (seems like it's N^M), use one single loop and then use / and % to calculate what the array index of each character should be. You'd better use longs as well, because N^M gets big fast.
Wikipedia has C code for the n-ary Gray code. It should be convertible to your problem by using the digits as offsets into your input array. You will need to do some dynamic allocation to handle the arbitrary length of your input. A related approach is to do nested loops, where you have an array of loop counters as long as your input, and another counter for which of those you are currently incrementing. E.g. printing all six-digit base-six numbers, needs to be modified for dynamic allocation but shows the principle:
int i;
int length = 5;
int max = 6;
int counters[length];
for (i=0; i<length; i++)
counters[i] = 0;
for(;;) {
for (i=length-1; i>=0; i--)
printf("%d", counters[i]);
printf("\n");
for(i=0; i<length; i++) {
counters[i]++;
if (counters[i] < max)
break;
else
counters[i] = 0;
}
if (i >= length)
break;
}
Python is very close to a pseudo code.
You can read the Python source to itertools.permutations and just replicate in C.
Here is the demo that this works:
#!/usr/bin/env python
import itertools
s='a1'
print set(itertools.permutations(s*len(s), len(s)))
Output:
set([('1', '1'), ('a', '1'), ('a', 'a'), ('1', 'a')])
Here is an even simpler way:
>>> s='a1'
>>> ['{}{}'.format(x,y) for x in s for y in s]
['aa', 'a1', '1a', '11']
>>> s='abc'
>>> ['{}{}{}'.format(x,y,z) for x in s for y in s for z in s]
['aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb',
'acc', 'baa', 'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca',
'bcb', 'bcc', 'caa', 'cab', 'cac', 'cba', 'cbb', 'cbc',
'cca', 'ccb', 'ccc']
To unwind a list comprehension, use NESTED LOOPS, like so:
>>> for x in s:
... for y in s:
... for z in s:
... print '{}{}{}'.format(x,y,z)
Well, I would number the possible combinations, loop through the numbers and convert.
For instance: to generate all size 3 combinations of the 10 symbols {'0', '1', ..., '9'}, I would loop from 0 to 999 and output "000" to "999".
In the same way (kinda), to generate all size 3 combinations of the 5 symbols {'a', 'b', ..., 'e'} I would loop from 0 to 5*5*5-1 and output the loop number in base 5, but with the symbols provided.
Write a function that will convert an integer into a string hexadecimal number, then convert that algorithm into a base 36 (a-z plus 0-9) number. Use one for loop to count from 1 to (digit count times base) and call your function each time.
1 becomes 1
10 becomes a
35 becomes z
36 becomes 10
46 becomes 1a
Related
I have N strings of bits (each of size M) X1[0..M], ..., XN[0..M]. I need the pseudocode/algorithm to find the smallest length subsequence (not necessarily contiguous) that is unique in each given string. For example,
If the strings are 011011, 011000, 010010 , the subsequence [2,4] (11, 10, 01) is different in each string. Or the subsequence [2, 4, 5] (111, 100, 010) . Or the subsequence [4, 5] (11, 00, 10).
But not the subsequence [0, 1, 5] (011, 010, 010) ---> Not unique in each string.
EDIT : 1 <= M <= 1000, 2 <= N <= 10.
EDIT : Currently, my solution is this :
The minimum length of subsequence will range between ceil(log2(N)) and N-1.
So, the pseudocode will be :
for i = ceil(log2(N)) to N-1 :
check all subsequence of size i
if any subsequence distinguish all N strings, return i
The first step can be done by generating all combinations mCi.
The second step can be done by extracting the subsequence for all N strings and checking if all of them are distinct.
But this algorithm is currently exponential complexity. I wanted to know if a better algorithm is possible.
EDIT : No, It isn't homework. It was asked in an interview.
i think something like this would work:
first:
create matriz A (mxm) and array B(m)
for each bit i from right to left, compute de decimal value of j word in A[i][j]
//that means A[i][j] holds the decimal value of word j until the i bit
in the same loop B[i] will hold if bit i from all words are the same.
if B[i] = true, it means that we dont need to look that position, cos it says nothing.
create deque D//to check if there is equal elements
create array C(m)
for each position P in [0...M] where B[i] = false :
for each bit i = P ... 0
for each word j
C[j] = C[j]*2 + word[j][i] //word[j][i] = word j in bit i
bool finished = true;
for each e in C:
if(D.count(e) > 0) {
finished = false;
break;
}
else{
D.add(e)
}
}
if(finished) return range(P...i);
D.clear()
not possible;
what this algorithm does is: starting from useful positions, it starts creating value for words from them, and in the moment you are able to add all of them in the deque (all of them are different), you are done finding a range where they differ (range is P - i + 1 sized).
You have to run this anyway for all i where B[i] = false, so in the worst case it should run about n³.
Note that there are some optimizations that can be done knowing the number of strings and their size, for example: if there are 10 strings of size 3, you know its impossible to distinguish (cos there arent different 10 different binaries of size 3). Given the number of strings, you can search only for (contiguous or not) sizes ceil(log(number of strings)). For example, 5 words cant differ in one bit, also they cant differ in 2 bits, but with 3 bits they can differ.
I came across a problem from a recent competition.
I was unable to figure out a solution, and no editorial for the question is yet available.
Question Link
I am quoting the problem statement here also in case the link doesn't work.
Find the number of integers n which are greater than or equal to A and less than or equal to B (A<= n <=B) and the decimal representation of 2^n ends in n.
Ex: 2^36 = 68719476736 which ends in “36”.
INPUT
The first line contains an integer T i.e. number of test cases. T lines follow, each containing two integers A and B.
Constraints
1 <= T <= 10^5
A<=B
A,B <= 10^150
OUTPUT
Print T lines each containing the answer to the corresponding testcase.
Sample Input
2
36 36
100 500
Sample Output
1
0
As often happens on programming competitions I have come up with an heuristics I have not proven, but seems plausible. I have written a short program to find the numbers up to 1000000 and they are:
36
736
8736
48736
948736
Thus my theory is the following - each consecutive number is suffixed with the previous one and only adds one digit. Hope this will set you on the right track for the problem. Note that if my assumption is right than you only need to find 150 numbers and finding each consecutive number requires checking 9 digits that may be added.
A general advice for similar problems - always try to find the first few numbers and think of some relation.
Also often it happens on a competition that you come up with a theory like the one I propose above, but have no time to prove it. You can't afford the time to prove it. Simply hope you are right and code.
EDIT: I believe I was able to prove my conjecture above(in fact I have missed some numbers -see end of the post). First let me point out that as v3ga states in a comment the algorithm above works up until 75353432948736 as no digit can be prepended to make the new number "interesting" as per the definition you give. However I completely missed another option - you may prepend some number of 0 and then add a non-zero digit.
I will now proof a lemma:
Lemma: if a1a2...an is an interesting number and n is more than 3, then a2...an also is interesting.
Proof:
2a1a2...an = 2a1*10n - 1*2a2a2...an
Now I will prove that 2a1*10n - 1*2a2a2...an is comparable to 2a2a2...an modulo 10n-1.
To do that lets prove that 2a1*10n - 1*2a2a2...an - 2a2a2...an is divisible by 10n-1.
2a1*10n - 1*2a2a2...an - 2a2a2...an =
2a2a2...an * (2a1*10n - 1 - 1)
a2a2...an is more than n-1 for the values we consider.
Thus all that's left to prove to have 10n-1 dividing the difference is that 5n-1 divides 2a1*10n - 1 - 1.
For this I will use Euler's theorem:
2phi(5n-1) = 1 (modulo 5n-1).
Now phi(5n-1) = 4*(5n-2) and for n >= 3 4*(5n-2) will divide a1*10n - 1(actually even solely 10n - 1).
Thus 2a1*10n - 1 gives remainder 1 modulo 5n-1 and so 5n-1 divides 2a1*10n - 1 - 1.
Consequently 10n-1 divides 2a2a2...an * (2a1*10n - 1 - 1) and so the last n - 1 digits of 2a1a2a2...an and 2a2a3a4...an are the same.
Now as a1a2a2...an is interesting the last n digits of 2a1a2a2...an are a1a2a2...an and so the last n-1 digits of 2a2a3a4...an are a2a3a4...an and consequently a2a3a4...an is also interesting. QED.
Use this lemma and you will be able to solve the problem. Please note that you may also prepend some zeros and then add a non-zero number.
In general, you can try solving these problems by finding some pattern in the output. Our team got this problem accepted at the contest. Our approach was to find a general pattern in the values that satisfy the criteria. If you print the first few such digits, then you will find the following pattern
36
736
8736
48736
948736
Thus the next number after 948736 should be of 7 digits and can be any one of 1948736, 2948736, 3948736, 4948736, 5948736, 6948736, 7948736, 8948736, 9948736. Thus check which value is valid and you have the next number. Continuing in this fashion you can back yourself to get all the 150 numbers.
But there is a problem here. There will be some numbers that do not immediately follow from the previous number by appending '1' to '9'. To counter this you can now start appending values from 10 to 99 and now check if there is a valid number or not. If there is still no valid number, then again try appending numbers from 100 to 999.
Now employing this hack, you will get all the 137 values that satisfy the criterion given in the question and easily answer all the queries. For example, working java code that implements this is shown here. It prints all the 137 values.
import java.io.*;
import java.math.*;
import java.util.*;
class Solution
{
public static void main(String[] args)throws java.lang.Exception{
new Solution().run();
}
void run()throws java.lang.Exception{
BigInteger[] powers = new BigInteger[152];
powers[0] = one;
for(int i=1; i<=150; i++){
powers[i] = powers[i-1].multiply(ten);
}
BigInteger[] answers = new BigInteger[152];
answers[2] = BigInteger.valueOf(36);
answers[3] = BigInteger.valueOf(736);
int last = 3;
for(int i=4; i<=150; i++){
int dif = i-last;
BigInteger start = ten.pow(dif-1);
BigInteger end = start.multiply(ten);
while(start.compareTo(end) < 0){
BigInteger newVal = powers[last].multiply(start);
newVal = newVal.add(answers[last]);
BigInteger modPow = pow(two, newVal, powers[i]);
if(modPow.equals(newVal)){
answers[i] = newVal;
System.out.println(answers[i]);
last = i;
break;
}
start = start.add(one);
}
}
}
BigInteger pow(BigInteger b, BigInteger e, BigInteger mod){
if(e.equals(zero)){
return one;
}
if(e.mod(two).equals(zero)){
BigInteger x = pow(b, e.divide(two), mod);
x = x.multiply(x).mod(mod);
return x;
}else{
BigInteger x = pow(b, e.divide(two), mod);
x = x.multiply(x).mod(mod);
x = x.multiply(two).mod(mod);
return x;
}
}
BigInteger ten = BigInteger.valueOf(10);
BigInteger zero = BigInteger.ZERO;
BigInteger one = BigInteger.ONE;
BigInteger two = BigInteger.valueOf(2);
}
This is very interesting property. During the contest, I found that 36 was the only number under 500 checking with python...
The property is : 2^36 last two digits are 36, last three digits are 736, so next number is 736. 2^736 has last three digits as 736, and next number is 8376...
And the series is : 36 , 736 , 8736 , 48736 , 948736 ...
And then started with BigInt class in C++.
But alas there was no time, and 4th problem wasn't solved. But after the contest, we did it in python.
here's link : Ideone it!
def powm(i):
j = 10
a = 1
while i:
if i % 2:
a = a * j
i /= 2
j *= j
return a
def power(n, i):
m = powm(i)
y = 1
x = 2
while n:
if n % 2 == 1:
y = y * x % m
x = x * x % m
n /= 2
return y
mylist = []
mylist.append(power(36, 2))
n = mylist[0]
print(n)
for i in range(3, 170):
p = power(n, i)
print p
if p != n:
mylist.append(p)
n = p
t = input()
while t:
x = raw_input().split(" ")
a = int(x[0])
b = int(x[1])
i = 0
#while i <= 150:
#print mylist[i]
#i += 1
#print power(8719476736,14)
while mylist[i] < a:
i += 1
ans = 0
while mylist[i] <= b:
i += 1
ans += 1
print ans
t -= 1
The final digits start to repeat after 20 increments. So for any n with the final digit 1, the final digit of the answer will be 2. So most values of n can be eliminated immediately.
2^1 = 2
2^21 = 2097152
2^101 = 2535301200456458802993406410752
2^2 = 4
2^22 = 4194304
2^42 = 4398046511104
In fact only two possibilities share a final digit:
2^14 = 16384
2^16 = 65536
2^34 = 17179869184
2^36 = 68719476736
If n is 14+20x or 16+20x, then it might work, so you'll need to check it. Otherwise, it cannot work.
I am not very good with such problems. But modular exponentiation appears to be key in your case.
Repeat for all n in the range A to B:
1. Find k, the no of digits in n. This can be done in O(logn)
2. Find 2^n (mod 10^k) using modular exponentiation and check if it is equal to n. This'll take O(n) time. (actually, O(n) multiplications)
EDIT
Actually, don't repeat the whole process for each n. Given 2^n (mod 10^k), we can find 2^(n+1) (mod 10^k) in constant time. Use this fact to speed it up further
EDIT - 2
This doesn't work for such large range.
Stumbled upon this interview question recently,
Given a 2-dimensional array of characters and a dictionary in which a word can be searched in O(1) time. Need to print all the words from array which are present in dictionary. Word can be formed in any direction but has to end at any edge of array.(Need not worry much about the dictionary)
Input:
a f h u n
e t a i r
a e g g o
t r m l p
Output:
after
hate
hair
air
eat
tea
Note: Here "egg" is not a dictionary word because its not ending at the edge of array.
I've seen similar questions before, but was never able to think of a good algorithm to solve these kind of problems. Any help on how to approach these kind of problems (forming words from arrays of characters) will be highly helpful.
(The only way I could think of is to find all possible permutations of characters in the 2D array, and check if it ends on the edge of the array, and check if the permutation is a valid word from the dictionary in O(1) time)
Turn the array into a graph so that each cell [i,j]
has an edge shared with each one of its 4 neighbors [i+1,j], [i-1,j], [i,j+1], [i,j-1].
Then run DFS at each array-edge-cell and and keep checking the dictionary whether
the word in reverse is in it.
You did not mention anything about a character can be used only once - so without this restriction is problem of "Can we generate k (or more) different words?" is undecideable.1.
(With a constraint on the number of "visites" per element there are finite number of possibilities and the claim and proof does not hold of course).
Proof:
It is known that there is no algorithm A that can decide if a terminating algorithm B returns true for k or more different inputs. (will look for citation for this claim later if needed, trust me for now).
We will show that given an algorithm A that says if there are k or more generated words - we can decide if there are k or more different inputs that yield "true":
Let the (terminating) algorithm that decides if there are k or
more generated words be M.
Without loss of generality - assume binary alphabet (we can represent everything with it).
Let:
array = 0 1
0 1
Note we can generate any binary word while walking on this array.
Algorithm A:
input: algorithm B, natural number n
output: true if and only if algorithm B answers "true" for n or more different inputs.
The algorithm:
(1) use B(word) as the black box dictionary - if the answer is true, then word is in dictionary.
(2) use array as the array.
(3) Run M on (array,dictionary,n), and answer like it.
Note that if M answered true -> there are n or more accepted words -> there are n or more different inputs to B that yields true (definition of dictionary and since we can generate every input with array) -> the answer to the problem is true.
(if the algorithm answered false the proof is similar).
QED
Conclusion:
If we can repeat a character in the array more then a once (or to be exact - unbounded number of times) - then the problem is unsolveable without any information on the dictionary.
(1) An undecideble problem is a problem where there is no algorithm that can answer TRUE/FALSE correctly in 100% of the cases - For every algorithm, there is some case where the algorithm will get "stuck" in an infinite loop (or give a wrong answer). The most common of "undecideable" problems is the Halting Problem - which says - there is no algorithm A that can take any algorithm B and answer if B stops for some input w.
My solution is:
I suppose that I have an M*N array and there is no restriction in searching words. For example 'rood' and 'door' are 2 different words as being reversed of each other.
Start from the first letter (left, top). In this case, it is 'a'. And check adjacents if there are any words in dictionary(suppose there are words starting with 'ae' and 'af' ) Check whether they are already words or not and the index of the last letter is 0 or M-1 or N-1. If not, add them to a queue to look later. By turns, check all queued substrings like this and finish this this phase by prosessing all values in queue. Then check second letter and go on up to the last member of array. Like this, you will be able to check all possible words.
It works on one of my problems like this but Im not sure if you are looking also for complexity.
import java.util.HashSet;
import java.util.Set;
/**
* Given a 2-dimensional array of characters and a
* dictionary in which a word can be searched in O(1) time.
* Need to print all the words from array which are present
* in dictionary. Word can be formed in any direction but
* has to end at any edge of array.
* (Need not worry much about the dictionary)
*/
public class DictionaryWord {
private static char[][] matrix = new char[][]{
{'a', 'f', 'h', 'u', 'n'},
{'e', 't', 'a', 'i', 'r'},
{'a', 'e', 'g', 'g', 'o'},
{'t', 'r', 'm', 'l', 'p'}
};
private static int dim_x = matrix.length;
private static int dim_y = matrix[matrix.length -1].length;
private static Set<String> wordSet = new HashSet<String>();
public static void main(String[] args) {
//dictionary
wordSet.add("after");
wordSet.add("hate");
wordSet.add("hair");
wordSet.add("air");
wordSet.add("eat");
wordSet.add("tea");
for (int x = 0; x < dim_x; x++) {
for (int y = 0; y < dim_y; y++) {
checkAndPrint(matrix[x][y] + "");
int[][] visitedMap = new int[dim_x][dim_y];
visitedMap[x][y] = 1;
recursion(matrix[x][y] + "", visitedMap, x, y);
}
}
}
private static void checkAndPrint(String word) {
if (wordSet.contains(word)) {
System.out.println(word);
}
}
private static void recursion(String word, int[][] visitedMap, int x, int y) {
for (int i = Math.max(x - 1, 0); i < Math.min(x + 2, dim_x); i++) {
for (int j = Math.max(y - 1, 0); j < Math.min(y + 2, dim_y); j++) {
if (visitedMap[i][j] == 1) {
continue;
} else {
int[][] newVisitedMap = new int[dim_x][dim_y];
for (int p = 0; p < dim_x; p++) {
for (int q = 0; q < dim_y; q++) {
newVisitedMap[p][q] = visitedMap[p][q];
}
}
newVisitedMap[i][j] = 1;
checkAndPrint(word + matrix[i][j]);
recursion(word + matrix[i][j], newVisitedMap, i, j);
}
}
}
}
}
Size of an array is n.All elements in the array are distinct in the range of [0 , n-1] except two elements.Find out repeated element without using extra temporary array with constant time complexity.
I tried with o(n) like this.
a[]={1,0,0,2,3};
b[]={-1,-1,-1,-1,-1};
i=0;
int required;
while(i<n)
{
b[a[i]]++;
if(b[a[i]==1)
required=a[i];
}
print required;
If there is no constraint on range of numbers i.e allowing out of range also.Is it possible get o(n) solution without temporary array.
XOR all the elements together, then XOR the result with XOR([0..n-1]).
This gives you missing XOR repeat; since missing!=repeat, at least one bit is set in missing XOR repeat.
Pick one of those set bits. Iterate over all the elements again, and only XOR elements with that bit set. Then iterate from 1 to n-1 and XOR those numbers that have that bit set.
Now, the value is either the repeated value or the missing value. Scan the elements for that value. If you find it, it's the repeated element. Otherwise, it's the missing value so XOR it with missing XOR repeat.
Look what is first and last number
Calculate SUM(1) of array elements without duplicate (like you know that sum of 1...5 = 1+2+3+4+5 = 15. Call it SUM(1)). As AaronMcSmooth pointed out, the formula is Sum(1, n) = (n+1)n/2.
Calculate SUM(2) of the elements in array that is given to you.
Subtract SUM(2) - SUM(1). Whoa! The result is the duplicate number (like if a given array is 1, 2, 3, 4, 5, 3, the SUM(2) will be 18. 18 - 15 = 3. So 3 is a duplicate).
Good luck coding!
Pick two distinct random indexes. If the array values at those indexes are the same, return true.
This operates in constant time. As a bonus, you get the right answer with probability 2/n * 1/(n-1).
O(n) without the temp array.
a[]={1,0,0,2,3};
i=0;
int required;
while(i<n)
{
a[a[i] % n] += n;
if(a[a[i] % n] >= 2 * n)
required = a[i] % n;
}
print required;
(Assuming of course that n < MAX_INT - 2n)
This example could be useful for int, char, and string.
char[] ch = { 'A', 'B', 'C', 'D', 'F', 'A', 'B' };
Dictionary<char, int> result = new Dictionary<char, int>();
foreach (char c in ch)
{
if (result.Keys.Contains(c))
{
result[c] = result[c] + 1;
}
else
{
result.Add(c, 1);
}
}
foreach (KeyValuePair<char, int> pair in result)
{
if (pair.Value > 1)
{
Console.WriteLine(pair.Key);
}
}
Console.Read();
Build a lookup table. Lookup. Done.
Non-temporary array solution:
Build lookup into gate array hardware, invoke.
The best I can do is O(n log n) in time and O(1) in space:
The basic idea is to perform a binary search of the values 0 through n-1, passing over the whole array of n elements at each step.
Initially, let i=0, j=n-1 and k=(i+j)/2.
On each run through the array, sum the elements whose values are in the range i to k, and count the number of elements in this range.
If the sum is equal to (k-i)*(k-i+1)/2 + i*(k-i+1), then the range i through k has neither the duplicate nor the omitted value. If the count of elements is less than k-i+1, then the range has the omitted value but not the duplicate. In either case, replace i by k+1 and k by the new value of (i+j)/2.
Else, replace j by k and k by the new value of (i+j)/2.
If i!=j, goto 2.
The algorithm terminates with i==j and both equal to the duplicate element.
(Note: I edited this to simplify it. The old version could have found either the duplicate or the omitted element, and had to use Vlad's difference trick to find the duplicate if the initial search turned up the omitted value instead.)
Lazy solution: Put the elements to java.util.Set one by one by add(E) until getting add(E)==false.
Sorry no constant-time. HashMap:O(N), TreeSet:O(lgN * N).
Based on #sje's answer. Worst case is 2 passes through the array, no additional storage, non destructive.
O(n) without the temp array.
a[]={1,0,0,2,3};
i=0;
int required;
while (a[a[i] % n] < n)
a[a[i++] % n] += n;
required = a[i] % n;
while (i-->0)
a[a[i]%n]-=n;
print required;
(Assuming of course that n < MAX_INT/2)
#include<stdio.h>
#include<conio.h>
main()
{
int i,j,k,x,y,n=4,a[]={1,2,3,4}; //n is the length of the array
for(i=0;i<n;i++)
{
for(k=0;k<(n-2);k++)
{
for(j=(n-1-k);j>=1;j--)
{
y=a[j];
a[j]=a[j-1];
a[j-1]=y;
for(x=0;x<n;x++)
{
printf("%d",a[x]);
}
printf("\t");
}
}
}
getch();
}
Some additional material (I'm a bit drunk, I will probably have to re-edit this tomorrow, so take it with a grain of salt):
Knuth and Sedgewick both covered permutations aeons ago.
Have a look at: http://www.princeton.edu/~rblee/ELE572Papers/p137-sedgewick.pdf
For n items you have n! permutations, so for 13 items you already have 6 227 020 800 permutations. So creating all permutations for a large set of items will become impossible pretty fast.
There are basically two sets of algorithms to create permutations, ranking/unranking and incremental change methods.
With ranking/unranking you have two methods rank and unrank.
Rank will give you the position of a permutation in the genereration order.
Unrank will give you the permutation that lies at integer m, with 0 >= m <= n! and n the amount of items you want to create permutations for.
This is useful for a variety of cases such as:
Creating a random permutation (you just create a random number from 0 to n! and call unrank(randomNumber)) and get the permutation at position randomNumber.
Creating sequences, getting the next permutation: You have a permutation p and call Rank(p) then Unrank(rank+1).
Incremental change methods:
These basically work through swapping and are more efficient than ranking/unranking:
From wikipedia, unordered generation:
function permutation(k, s) {
for j = 2 to length(s) {
swap s[(k mod j) + 1] with s[j]; // note that our array is indexed starting at 1
k := k / j; // integer division cuts off the remainder
}
return s;
}
Change this:
for(k=0;k<(n-2);k++)
to this:
for(k=0;k<(n-1);k++)
Also, try using more descriptive variable names...
I don't know the point of your program, but you may try to read the implementation of std::next_permutation. Generating all permutations with loops is somewhat tricky and I prefer using recursion.