shuffle card deck issues in language agnostic [closed] - language-agnostic

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Not so long ago I was in an interview, that required solving two very interesting problems. I'm curious how would you approach the solutions.
Problem 1 :
Product of everything except current
Write a function that takes as input two integer arrays of length len, input and index, and generates a third array, result, such that:
result[i] = product of everything in input except input[index[i]]
For instance, if the function is called with len=4, input={2,3,4,5}, and index={1,3,2,0}, then result will be set to {40,24,30,60}.
IMPORTANT: Your algorithm must run in linear time.
Problem 2 : ( the topic was in one of Jeff posts )
Shuffle card deck evenly
Design (either in C++ or in C#) a class Deck to represent an ordered deck of cards, where a deck contains 52 cards, divided in 13 ranks (A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K) of the four suits: spades (?), hearts (?), diamonds (?) and clubs (?).
Based on this class, devise and implement an efficient algorithm to shuffle a deck of cards. The cards must be evenly shuffled, that is, every card in the original deck must have the same probability to end up in any possible position in the shuffled deck.
The algorithm should be implemented in a method shuffle() of the class Deck:
void shuffle()
What is the complexity of your algorithm (as a function of the number n of cards in the deck)?
Explain how you would test that the cards are evenly shuffled by your method (black box testing).
P.S. I had two hours to code the solutions

First question:
int countZeroes (int[] vec) {
int ret = 0;
foreach(int i in vec) if (i == 0) ret++;
return ret;
}
int[] mysticCalc(int[] values, int[] indexes) {
int zeroes = countZeroes(values);
int[] retval = new int[values.length];
int product = 1;
if (zeroes >= 2) { // 2 or more zeroes, all results will be 0
for (int i = 0; i > values.length; i++) {
retval[i] = 0;
}
return retval;
}
foreach (int i in values) {
if (i != 0) product *= i; // we have at most 1 zero, dont include in product;
}
int indexcounter = 0;
foreach(int idx in indexes) {
if (zeroes == 1 && values[idx] != 0) { // One zero on other index. Our value will be 0
retval[indexcounter] = 0;
}
else if (zeroes == 1) { // One zero on this index. result is product
retval[indexcounter] = product;
}
else { // No zeros. Return product/value at index
retval[indexcounter] = product / values[idx];
}
indexcouter++;
}
return retval;
}
Worst case this program will step through 3 vectors once.

For the first one, first calculate the product of entire contents of input, and then for every element of index, divide the calculated product by input[index[i]], to fill in your result array.
Of course I have to assume that the input has no zeros.

Tnilsson, great solution ( because I've done it the exact same way :P ).
I don't see any other way to do it in linear time. Does anybody ? Because the recruiting manager told me, that this solution was not strong enough.
Are we missing some super complex, do everything in one return line, solution ?

A linear-time solution in C#3 for the first problem is:-
IEnumerable<int> ProductExcept(List<int> l, List<int> indexes) {
if (l.Count(i => i == 0) == 1) {
int singleZeroProd = l.Aggregate(1, (x, y) => y != 0 ? x * y : x);
return from i in indexes select l[i] == 0 ? singleZeroProd : 0;
} else {
int prod = l.Aggregate(1, (x, y) => x * y);
return from i in indexes select prod == 0 ? 0 : prod / l[i];
}
}
Edit: Took into account a single zero!! My last solution took me 2 minutes while I was at work so I don't feel so bad :-)

Product of everything except current in C
void product_except_current(int input[], int index[], int out[],
int len) {
int prod = 1, nzeros = 0, izero = -1;
for (int i = 0; i < len; ++i)
if ((out[i] = input[index[i]]) != 0)
// compute product of non-zero elements
prod *= out[i]; // ignore possible overflow problem
else {
if (++nzeros == 2)
// if number of zeros greater than 1 then out[i] = 0 for all i
break;
izero = i; // save index of zero-valued element
}
//
for (int i = 0; i < len; ++i)
out[i] = nzeros ? 0 : prod / out[i];
if (nzeros == 1)
out[izero] = prod; // the only non-zero-valued element
}

Here's the answer to the second one in C# with a test method. Shuffle looks O(n) to me.
Edit: Having looked at the Fisher-Yates shuffle, I discovered that I'd re-invented that algorithm without knowing about it :-) it is obvious, however. I implemented the Durstenfeld approach which takes us from O(n^2) -> O(n), really clever!
public enum CardValue { A, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, J, Q, K }
public enum Suit { Spades, Hearts, Diamonds, Clubs }
public class Card {
public Card(CardValue value, Suit suit) {
Value = value;
Suit = suit;
}
public CardValue Value { get; private set; }
public Suit Suit { get; private set; }
}
public class Deck : IEnumerable<Card> {
public Deck() {
initialiseDeck();
Shuffle();
}
private Card[] cards = new Card[52];
private void initialiseDeck() {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 13; ++j) {
cards[i * 13 + j] = new Card((CardValue)j, (Suit)i);
}
}
}
public void Shuffle() {
Random random = new Random();
for (int i = 0; i < 52; ++i) {
int j = random.Next(51 - i);
// Swap the cards.
Card temp = cards[51 - i];
cards[51 - i] = cards[j];
cards[j] = temp;
}
}
public IEnumerator<Card> GetEnumerator() {
foreach (Card c in cards) yield return c;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
foreach (Card c in cards) yield return c;
}
}
class Program {
static void Main(string[] args) {
foreach (Card c in new Deck()) {
Console.WriteLine("{0} of {1}", c.Value, c.Suit);
}
Console.ReadKey(true);
}
}

In Haskell:
import Array
problem1 input index = [(left!i) * (right!(i+1)) | i <- index]
where left = scanWith scanl
right = scanWith scanr
scanWith scan = listArray (0, length input) (scan (*) 1 input)

Vaibhav, unfortunately we have to assume, that there could be a 0 in the input table.

Second problem.
public static void shuffle (int[] array)
{
Random rng = new Random(); // i.e., java.util.Random.
int n = array.length; // The number of items left to shuffle (loop invariant).
while (n > 1)
{
int k = rng.nextInt(n); // 0 <= k < n.
n--; // n is now the last pertinent index;
int temp = array[n]; // swap array[n] with array[k] (does nothing if k == n).
array[n] = array[k];
array[k] = temp;
}
}
This is a copy/paste from the wikipedia article about the Fisher-Yates shuffle. O(n) complexity

Tnilsson, I agree that YXJuLnphcnQ solution is arguably faster, but the idee is the same. I forgot to add, that the language is optional in the first problem, as well as int the second.
You're right, that calculationg zeroes, and the product int the same loop is better. Maybe that was the thing.

Tnilsson, I've also uset the Fisher-Yates shuffle :). I'm very interested dough, about the testing part :)

Trilsson made a separate topic about the testing part of the question
How to test randomness (case in point - Shuffling)
very good idea Trilsson:)

YXJuLnphcnQ, that's the way I did it too. It's the most obvious.
But the fact is, that if you write an algorithm, that just shuffles all the cards in the collection one position to the right every time you call sort() it would pass the test, even though the output is not random.

Shuffle card deck evenly in C++
#include <algorithm>
class Deck {
// each card is 8-bit: 4-bit for suit, 4-bit for value
// suits and values are extracted using bit-magic
char cards[52];
public:
// ...
void shuffle() {
std::random_shuffle(cards, cards + 52);
}
// ...
};
Complexity: Linear in N. Exactly 51 swaps are performed. See http://www.sgi.com/tech/stl/random_shuffle.html
Testing:
// ...
int main() {
typedef std::map<std::pair<size_t, Deck::value_type>, size_t> Map;
Map freqs;
Deck d;
const size_t ntests = 100000;
// compute frequencies of events: card at position
for (size_t i = 0; i < ntests; ++i) {
d.shuffle();
size_t pos = 0;
for(Deck::const_iterator j = d.begin(); j != d.end(); ++j, ++pos)
++freqs[std::make_pair(pos, *j)];
}
// if Deck.shuffle() is correct then all frequencies must be similar
for (Map::const_iterator j = freqs.begin(); j != freqs.end(); ++j)
std::cout << "pos=" << j->first.first << " card=" << j->first.second
<< " freq=" << j->second << std::endl;
}
As usual, one test is not sufficient.

Related

Why is for loop only out putting first and last entries

This is what is being asked to do...
Write an application that inputs five numbers, each between 10 and 100, inclusive. As each number is read, display it only if it’s not a duplicate of a number already read. Provide for the “worst case,” in which all five numbers are different. Use the smallest possible array to solve this problem. Display the complete set of unique values input after the user enters each new value.
This is the code I have. It compiles and runs, but only outputs the first and last entries of the unique list. Any input greatly appreciated! Thanks in advance.
import java.util.Scanner;
public class DuplicateElimination{
// sets helper functions
public static boolean isIn(int x, int[]y)
{
boolean isIn = false;// sets boolean to false
for (int i=0; i<y.length; i++)// sets for loop to run for length of array
{
if(y[i]==x)
{
isIn = true;
}
}
return isIn;
}
public static int[] append(int x, int[] y)// going to change what has already been set. creates integer array
{
int len = y.length +1;// sets length
int[] a = new int[len];// initializes new array
for (int i=0; i<y.length; i++); // goes through length of y
{
int i=0;
a[i] = y[i];
}
a[y.length] =x;
return a;
}
public static void main(String[] args)// sets main
{
Scanner input = new Scanner (System.in);// sets scanner to read input info
int[]uniqueList = new int[1];
uniqueList[0] = 0;// sets unique list to 0
System.out.print("Enter an integer between 10 and 100:");// prompts input from user
int entered = input.nextInt();// inputs value from user
System.out.printf("This is the first time %d has been entered\n", entered);// adds first entered # to unique list
uniqueList[0] = entered;// adds entered value to unique list
for (int i=0; i<4; i++)// sets loop to find unique values
{
System.out.print("Enter an integer between 10 and 100:");// prompts use
entered = input.nextInt();// inputs value
if(isIn (entered, uniqueList) == false)// calls is in function
{
System.out.printf("This is the first time %d has been entered\n", entered);
uniqueList = append(entered, uniqueList);// puts entered values in unique values on list
}
}
System.out.println("The complete list of unique values entered is:");
for(int i =0; i< uniqueList.length; i++)// runs through list to check for unique #s
{
System.out.printf("Unique value %d: is %d\n", i + 1, uniqueList[i]);// outputs list
}
}// ends main
}// ends class
in the append part change your for loop to:
for (int i=0;i<y.length;i++)
a[i]=y[i];
it didn't work because of for (int i=0; i<y.length; i++); the semi-colon is hijacking your loop as for why the result is as it is, your
{
int i=0;
a[i] = y[i];
}
a[y.length] =x;
return a;
part is just copying the first element of y into a and then copying the new element in the last cel of a
import java.util.*;
class Example{
public static void main(String args[]){
int[] xr = new int[5];
Scanner input = new Scanner (System.in);
System.out.println("Input five different integers between 10 and 100 below");
L1: for (int i = 0; i < xr.length; i++){
System.out.print("\tInput number "+(i+1)+" : ");
xr[i] = input.nextInt();
for(;xr[i]<=10 || xr[i]>=100;){
i--;
System.out.println("\t Error : You entered number is not between 10 and 100.");
continue L1;
}
for (int x = 0; x < i; x++){
if(xr[x] == xr[i]){
i--;
System.out.println("\tError : You cannot use duplicate numbers.");
continue L1;
}
}
}
System.out.println(Arrays.toString(xr));
}
}

Explanation of test case in the prisoner wall jump program

This would be the general problem statement:
A prisoner escapes from the jail by jumping over N walls each with height of each wall given in an array. He can jump x meters of height, but after every jump he slips y meters due to some uncontrollable factors(wind, slippery wall, etc).
Similar problem statement mentioned here
The programming task given was to debug a function which included four parameters -
NoOfJumps(int x, int y, int N, int Height[])
Number of meters he jumps
Number of meters he slips down the wall
Number of walls
Height of the walls as an array
The first test case was for parameters - (10, 1, 1, {10})
10 being the meters he jumps, 1 meter he slips down, Number of walls being 1, and height of the wall being 10. Now:
effectiveJump = x - y = 9.
So he would have to jump twice to jump over the walls. So, this function should return 2 (total number of jumps required to escape).
There was also another test case for the parameters - (3, 1, 5, {20,5,12,11,3})
3 being the meters he jumps, 1 meter he slips down, Number of walls being 5, and height of the walls given as 20m, 5m, 12m, 11m, 3m. Now:
effectiveJump = x - y = 2.
We were given the output for the above parameter values as 24.
NoOfJumps(3, 1, 5, {20,5,12,11,3})
I can't understand how this output value is obtained. How exactly are the walls arranged?
I can only think of one solution for the corner case, i.e, when the person jumps over the wall
(when (x) > remaining height of the wall),
he should not slip down else I can't obtain the required solution.
For example, in the second test case at first wall, when the person is at 18m height, and he jumps 3m to 21m and doesn't slip down as he has crossed that wall. Next he starts jumping from 21 and not 20. The sequence of jumping would be :
0->2->4->6->8->10->12->14->16->18->21->23->26->28->30->32->34->36->39->41->43->45->47->50->53
Assuming walls at height, 20, 25, 37, 48, 51.
Is this a correct assumption for solving the problem?
C code on given case 2, will work for case 1 on changing the
parameters to (10,1,1,10).
#include<conio.h>
#include<stdio.h>
int jump(int x,int y,int n,int z[]);
int jump(int x,int y,int n,int z[])
{
int i, j, countjump, total = 0, extra = 0;
clrscr();
printf("\n%d\n", n);
for (i = 0; i < n; i++) {
printf("\n%d", z[i]);
}
printf("\n");
for (j = 0; j < n; j++) {
countjump = 1;
z[j] = z[j] + (extra) - x;
while (z[j] >= 0) {
z[j] = z[j] + y;
z[j] = z[j] - x;
countjump = countjump + 1;
if (z[j] < 0) {
extra = z[j];
}
}
total = (countjump + total);
}
return total;
}
void main()
{
int res, manjump = 3, slip = 1, nwalls = 5;
int wallheights[] = {20, 5, 12, 11, 3};
clrscr();
res = jump(manjump, slip, nwalls, wallheights);
printf("\n\ntotal jumps:%d", res);
getch();
}
Try this code. May not be optimized
$input1 = Jump Height
$input2 = Slipage
$input = Array of walls height
function GetJumpCount($input1,$input2,$input3)
{
$jumps = 0;
$wallsCrossed = 0;
while($wallsCrossed != count($input3)){
$jumps++;
$input3[$wallsCrossed] = $input3[$wallsCrossed] - $input1;
if($input3[$wallsCrossed] > 0){
$input3[$wallsCrossed] = $input3[$wallsCrossed] + $input2;
}else{
$wallsCrossed++;
}
}
return $jumps;
}
The walls come one after another. After jumping wall one the position should start from zero and not from the last jump height. For the first case the output should really be 1 as the height and jump are same. In the second test case, 24 is the right output.
I've seen the exact same question on techgig contest. For the first test case the output should be 1. The test case had been explained by themselves where there is no slipping if the jump and height are same.
Try this
You don't require the number of walls as it equals to size of array
public class Jump {
public static void main(String[] a) {
int jump = 3;
int slip = 1;
int[] hights = {20,5,12,11,3};
int count = 0;
for (int hight : hights) {
int temp = hight - jump;
if (temp >= 0) {
count = count + temp / (jump - slip)+1;
}
if (temp % (jump - slip) > 0) {
count++;
}
}
System.out.println(count);
}
}
Logic is here Plz check if this solves your problem.
package puzeels;
public class Jump
{
int jump=6;
int slip=1;
int numberOfWals=4;
int height[] ={21,16,10,5};
static int count=0;
int wallheight=0;
private int findJump()
{
for(int i=0;i<height.length;i++)
{
wallheight=height[i];
while((wallheight>0))
{
count=count+1;
wallheight=wallheight-(jump-slip);
System.out.println(wallheight+" "+count);
}
System.out.println("Out of while loop");
}
return count;
}
public static void main(String arr[])
{
Jump obj = new Jump();
int countOfJumps=obj.findJump();
System.out.println("number of jumps is==> "+countOfJumps);
}
}
You can use this one.
Sample Code
public static int calculateJumps(int X, int Y, int height[]) {
int tn=0,n;
for(int i=0; i<height.length; i++) {
if(height[i]<=X) {
tn+=1;
continue;
}
n=((height[i]-X)/(X-Y));
n+=height[i]-((X-Y)*n)==X?1:2;
tn+=n;
}
return tn;
}
You need to pass only X , Y and Array than you can get you output.
I think 12 is a wrong answer, as I tried this code I got 11, last jump doesn`t have a slip:
public static void main(String [] args) {
int T;
int jcapacity, jslip, nwalls;
//BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
T = sc.nextInt();
jcapacity = sc.nextInt();
jslip = sc.nextInt();
nwalls = sc.nextInt();
int [] wallHeightArr = new int [nwalls];
for (int i = 0; i< nwalls; i++) {
wallHeightArr[i] = sc.nextInt();
}
sc.close();
while(T-->0) {
int distance = log(jcapacity,jslip,wallHeightArr);
System.out.println(distance);
}
}
private static int log(int jcapacity, int jslip, int[] wallHeightArr) {
// TODO Auto-generated method stub
int distance = 0;
for(int i = 0; i< wallHeightArr.length; i++) {
int cHeight = 0;
int count = 0;
while (wallHeightArr[i] - cHeight > jcapacity) {
cHeight += (jcapacity - jslip);
count++;
}
count++;
distance += count;
}
return distance;
}
def jumpTheifCount(arr, X, Y):
jump = 0
remheight = 0
for i in range(len(arr)):
if X == arr[i]:
jump = jump + 1
continue
if X < arr[i]:
jump = jump + 1
remheight = arr[i] - X + Y
if remheight > X:
jump = jump + 1
remheight = arr[i] - X + Y
if remheight < X:
jump = jump + 1
continue
return jump
arr = [11, 10, 10, 9]
X = 10
Y = 1
print(jumpTheifCount(arr, X, Y))
check if this solves your problem
def GetJumpCount(jump, slips, walls):
"""
#jump:int, Height of 1 jump
#slips:int, height of slip
#walls:array, height of walls
"""
jumps = []
for wall_height in walls:
wall_jump = 1
wall_height -= jump
while wall_height > 0:
wall_height += slips
wall_height -= jump
wall_jump += 1
jumps.append(wall_jump)
return sum(jumps)

Which algorithms are available to solve Tic Tac Toe?

What algorithms are available to solve Tic Tac Toe? Especially with board size 4 * 4 or bigger instead of 3 * 3? I tried 4 * 4 with Minimax & alpha-beta pruning but the pc seems to hang and throws exceptions on stack overflow.
I saw these source code written in javascript but I don't know which algorithm it uses, could anyone clarify it for me?
http://js-x.com/page/javascripts__example.html?view=153
try to do cut-offs in certain depth... i don't think you need more than 4 or 5 of depth to make a perfect move.
(java for 3*3 one-dim board with depth):
int minimax(int turn, int depth) { // turn(side to move) is 1 or -1
int val = -turn; // worst value for that turn
int result = NULVAL;
if (wins()) return turn; // evaluate board (board is a field)
if (depth == 0) return DRAW;
for (int i = 0; i < 9; i++) {
if (board[i] == EMPTY) {
board[i] = turn; // make move
result = minimax(-turn, depth - 1);
board[i] = EMPTY; // delete move
if (result == turn)
return turn; // sees win
if (result == DRAW)
val = result;
}
}
// if result keeps NULVAL: couldn't make a move (board is full)
if (result == NULVAL) return DRAW;
return val;
}

Rating the quality of string matches

What would be the best way to compare a pattern with a set of strings, one by one, while rating the amount with which the pattern matches each string? In my limited experience with regex, matching strings with patterns using regex seems to be a pretty binary operation...no matter how complicated the pattern is, in the end, it either matches or it doesn't. I am looking for greater capabilities, beyond just matching. Is there a good technique or algorithm that relates to this?
Here's an example:
Lets say I have a pattern foo bar and I want to find the string that most closely matches it out of the following strings:
foo for
foo bax
foo buo
fxx bar
Now, none of these actually match the pattern, but which non-match is the closest to being a match? In this case, foo bax would be the best choice, since it matches 6 out of the 7 characters.
Apologies if this is a duplicate question, I didn't really know what exactly to search for when I looked to see if this question already exists.
This one works, I checked with Wikipedia example distance between "kitten" and "sitting" is 3
public class LevenshteinDistance {
public static final String TEST_STRING = "foo bar";
public static void main(String ...args){
LevenshteinDistance test = new LevenshteinDistance();
List<String> testList = new ArrayList<String>();
testList.add("foo for");
testList.add("foo bax");
testList.add("foo buo");
testList.add("fxx bar");
for (String string : testList) {
System.out.println("Levenshtein Distance for " + string + " is " + test.getLevenshteinDistance(TEST_STRING, string));
}
}
public int getLevenshteinDistance (String s, String t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
int p[] = new int[n+1]; //'previous' cost array, horizontally
int d[] = new int[n+1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i<=n; i++) {
p[i] = i;
}
for (j = 1; j<=m; j++) {
t_j = t.charAt(j-1);
d[0] = j;
for (i=1; i<=n; i++) {
cost = s.charAt(i-1)==t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
}
That's an interesting question! The first thing that came to mind is that the way regular expressions are matched is by building a DFA. If you had direct access to the DFA that was built for a given regex (or just built it yourself!) you could run the input measure the distance from the last state you transitioned to and an accept state, using a shortest path as a measure of how close it was to being accepted, but I'm not aware of any libraries that would let you do that easily and even this measure probably wouldn't exactly map onto your intuition in a number of cases.

Best algorithm to find all possible permutation of given binary bits

I am looking for an optimal algorithm to find out remaining all possible permutation
of a give binary number.
For ex:
Binary number is : ........1. algorithm should return the remaining 2^7 remaining binary numbers, like 00000001,00000011, etc.
Thanks,
sathish
The example given is not a permutation!
A permutation is a reordering of the input.
So if the input is 00000001, 00100000 and 00000010 are permutations, but 00000011 is not.
If this is only for small numbers (probably up to 16 bits), then just iterate over all of them and ignore the mismatches:
int fixed = 0x01; // this is the fixed part
int mask = 0x01; // these are the bits of the fixed part which matter
for (int i=0; i<256; i++) {
if (i & mask == fixed) {
print i;
}
}
to find all you aren't going to do better than looping over all numbers e.g. if you want to loop over all 8 bit numbers
for (int i =0; i < (1<<8) ; ++i)
{
//do stuff with i
}
if you need to output in binary then look at the string formatting options you have in what ever language you are using.
e.g.
printf("%b",i); //not standard in C/C++
for calculation the base should be irrelavent in most languages.
I read your question as: "given some binary number with some bits always set, create the remaining possible binary numbers".
For example, given 1xx1: you want: 1001, 1011, 1101, 1111.
An O(N) algorithm is as follows.
Suppose the bits are defined in mask m. You also have a hash h.
To generate the numbers < n-1, in pseudocode:
counter = 0
for x in 0..n-1:
x' = x | ~m
if h[x'] is not set:
h[x'] = counter
counter += 1
The idea in the code is to walk through all numbers from 0 to n-1, and set the pre-defined bits to 1. Then memoize the resulting number (iff not already memoized) by mapping the resulting number to the value of a running counter.
The keys of h will be the permutations. As a bonus the h[p] will contain a unique index number for the permutation p, although you did not need it in your original question, it can be useful.
Why are you making it complicated !
It is as simple as the following:
// permutation of i on a length K
// Example : decimal i=10 is permuted over length k= 7
// [10]0001010-> [5] 0000101-> [66] 1000010 and 33, 80, 40, 20 etc.
main(){
int i=10,j,k=7; j=i;
do printf("%d \n", i= ( (i&1)<< k + i >>1); while (i!=j);
}
There are many permutation generating algorithms you can use, such as this one:
#include <stdio.h>
void print(const int *v, const int size)
{
if (v != 0) {
for (int i = 0; i < size; i++) {
printf("%4d", v[i] );
}
printf("\n");
}
} // print
void visit(int *Value, int N, int k)
{
static level = -1;
level = level+1; Value[k] = level;
if (level == N)
print(Value, N);
else
for (int i = 0; i < N; i++)
if (Value[i] == 0)
visit(Value, N, i);
level = level-1; Value[k] = 0;
}
main()
{
const int N = 4;
int Value[N];
for (int i = 0; i < N; i++) {
Value[i] = 0;
}
visit(Value, N, 0);
}
source: http://www.bearcave.com/random_hacks/permute.html
Make sure you adapt the relevant constants to your needs (binary number, 7 bits, etc...)
If you are really looking for permutations then the following code should do.
To find all possible permutations of a given binary string(pattern) for example.
The permutations of 1000 are 1000, 0100, 0010, 0001:
void permutation(int no_ones, int no_zeroes, string accum){
if(no_ones == 0){
for(int i=0;i<no_zeroes;i++){
accum += "0";
}
cout << accum << endl;
return;
}
else if(no_zeroes == 0){
for(int j=0;j<no_ones;j++){
accum += "1";
}
cout << accum << endl;
return;
}
permutation (no_ones - 1, no_zeroes, accum + "1");
permutation (no_ones , no_zeroes - 1, accum + "0");
}
int main(){
string append = "";
//finding permutation of 11000
permutation(2, 6, append); //the permutations are
//11000
//10100
//10010
//10001
//01100
//01010
cin.get();
}
If you intend to generate all the string combinations for n bits , then the problem can be solved using backtracking.
Here you go :
//Generating all string of n bits assuming A[0..n-1] is array of size n
public class Backtracking {
int[] A;
void Binary(int n){
if(n<1){
for(int i : A)
System.out.print(i);
System.out.println();
}else{
A[n-1] = 0;
Binary(n-1);
A[n-1] = 1;
Binary(n-1);
}
}
public static void main(String[] args) {
// n is number of bits
int n = 8;
Backtracking backtracking = new Backtracking();
backtracking.A = new int[n];
backtracking.Binary(n);
}
}