using a function to compare integers and find the position where one value is even and the other is odd c++ - function

/*
Description:
Write a function called digitsOpposite. The function has two integer parameters x and y that are
positive and have the same number of digits. It returns the number of positions where one number
has an even digit and the other has an odd one. For example, if the function was applied to 17345
and 97813 it would return 2 because the third digits are 3 and 8 and the fourth ones are 4 and 1.
(In both cases one of these is even and the other is odd.)
Problem: my code is not printing the desired output. HELP PLEASE!! I am a beginner. Thanks.
*/
#include <iostream>
using namespace std;
// declare function
int digitsOpposite(int x, int y){
int lastV1, lastV2, leftV1, leftV2;
leftV1 = 0,
leftV2 = 0;
lastV1 = 0;
lastV2 = 0;
for(int i = 5; i > 0; i--){
leftV1 += x; // 17345
leftV2 += y; // 97813
lastV1 += leftV1 % 2; //5
lastV2 += leftV2 % 2; //3
if((lastV1 == 0)&&( lastV2 != 0))
{
break;
return i;
}
else{
leftV1 += leftV1 / 10; // 1734
leftV2 += leftV2 / 10; // 9781
}
}
}
int main(){
cout <<"The position of the number is: " << digitsOpposite(17345, 97813);
return 0;
}

Related

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)

What is the best way to make these function into a class? Or multiple classes?

I am looking for any advice on how to turn a function into a class. I will enter a program below. It is long. I feel i should place the whole thing in for context. I need to rewrite it so that i will use classes in place of the three functions.
#include <iostream>
#include <string>
using namespace std;
// Do not change these function prototypes:
void readBig(int[]);
void printBig(int[]);
void addBig(int[], int[], int[]);
// This constant should be 100 when the program is finished.
const int MAX_DIGITS = 100;
int main()
{
// Declare the three numbers, the first, second and the sum:
int number1[MAX_DIGITS], number2[MAX_DIGITS], sum[MAX_DIGITS];
bool finished = false;
char response;
while (! finished)
{
cout << "Please enter a number up to " << MAX_DIGITS << " digits: ";
readBig(number1);
cout << "Please enter a number up to " << MAX_DIGITS << " digits: ";
readBig(number2);
addBig(number1, number2, sum);
printBig(number1);
cout << "\n+\n";
printBig(number2);
cout << "\n=\n";
printBig(sum);
cout << "\n";
cout << "test again?";
cin>>response;
cin.ignore(900,'\n');
finished = toupper(response)!= 'Y';
}
return 0;
}
//ReadBig will read a number as a string,
//It then converts each element of the string to an integer and stores it in an integer array.
//Finally, it reverses the elements of the array so that the ones digit is in element zero,
//the tens digit is in element 1, the hundreds digit is in element 2, etc.
//AddBig adds the corresponding digits of the first two arrays and stores the answer in the third.
//In a second loop, it performs the carry operation.
//PrintBig uses a while loop to skip leading zeros and then uses a for loop to print the number.
//FUNCTIONS GO BELOW
void readBig(int number[MAX_DIGITS])
{
string read="";
cin>>read;
int len,i, save=0;
len= read.length();
while(i<MAX_DIGITS){
number[i]=0;
i++;
}
for (i=0; i <= len-1; i++){
number[i] = int (read.at(i)-'0');
}
for (i=0;i<=len/2-1;i++){
save=number[i];
number[i]=number[len-1-i];
number[len-1-i]=save;
}
}
void printBig(int number[MAX_DIGITS])
{
int digit=MAX_DIGITS-1;
while(number[digit]==0){
digit--;
}
for (int i=digit; i>=0; i--)
{cout<<number[i];
}
}
void addBig(int number1[MAX_DIGITS], int number2[MAX_DIGITS], int sum[MAX_DIGITS])
{
// The code below sums the arrays.
for (int i = MAX_DIGITS - 1; i >= 0; i--)
{
sum[i] = number1[i] + number2[i];
if (sum[i] > 9 && i < MAX_DIGITS - 1)
{
sum[i + 1] += 1;
sum[i] -= 10;
}
}
}

function pointers returned by functions

I'm trying to learn pointers in C++, but seems that it get more complicated...
In the main loop
int i;
for (i = 0; i < 5; ++i){
if (fun == arrfun[i]) break;
}
How is that fun==arrfun[i] at fun2 if both fun and arrfun start looping form 0? Hence they should equal at log(x) instead. How could I loop to sin or cos, etc?
#include <iostream>
#include <cmath>
using namespace std;
typedef double(*FUNDtoD)(double);
typedef FUNDtoD ARRFUN[];
FUNDtoD funmax(ARRFUN, double);
double fun0(double x) { return log(x); }
double fun1(double x) { return x*x; }
double fun2(double x) { return exp(x); }
double fun3(double x) { return sin(x); }
double fun4(double x) { return cos(x); }
int main() {
ARRFUN arrfun = { fun0, fun1, fun2, fun3, fun4 };
FUNDtoD fun = funmax(arrfun, 1);
int i;
for (i = 0; i < 5; ++i){
if (fun == arrfun[i]) break;
}
cout.precision(14);
cout << "Largest value at x=1 assumed by function # "
<< i << ".\nThe value is " << fun(2) << endl;
return 0;
}
FUNDtoD funmax(ARRFUN f, double x){
double m = f[0](x), z;
int k = 0;
for (int i = 1; i < 5; i++){
if ((z = f[i](x)) > m) {
m = z;
k = i;
}
}
return f[k];
}
I don't understand how function FUNDtoD funmax is working at the bottom, could somebody clarify it please, many thanks.
How is that fun==arrfun[i] at fun2 if both fun and arrfun start looping form 0? > Hence they should equal at log(x) instead. How could I loop to sin or cos, etc?
fun is not being looped, the same pointer is checked against each function pointer stored in the array (arrfun). It is simply trying to find the index of the returned function pointer. If sin(x) gave the highest value then that loop would finish with a 4 in i.
don't understand how function FUNDtoD funmax is working at the bottom, could
somebody clarify it please, many thanks.
It breaks down as follows:
Firstly it performs m = f0;
f[0] -> fun0 so the result is m = log( x );
Next it steps through the other 4 functions and tests whether the operation on x results in a higher valuer than the previous. It then stores the index of the function that returned the highest value.
Finally it returns that function pointer.

How would you calculate all possible permutations of 0 through N iteratively?

I need to calculate permutations iteratively. The method signature looks like:
int[][] permute(int n)
For n = 3 for example, the return value would be:
[[0,1,2],
[0,2,1],
[1,0,2],
[1,2,0],
[2,0,1],
[2,1,0]]
How would you go about doing this iteratively in the most efficient way possible? I can do this recursively, but I'm interested in seeing lots of alternate ways to doing it iteratively.
see QuickPerm algorithm, it's iterative : http://www.quickperm.org/
Edit:
Rewritten in Ruby for clarity:
def permute_map(n)
results = []
a, p = (0...n).to_a, [0] * n
i, j = 0, 0
i = 1
results << yield(a)
while i < n
if p[i] < i
j = i % 2 * p[i] # If i is odd, then j = p[i], else j = 0
a[j], a[i] = a[i], a[j] # Swap
results << yield(a)
p[i] += 1
i = 1
else
p[i] = 0
i += 1
end
end
return results
end
The algorithm for stepping from one permutation to the next is very similar to elementary school addition - when an overflow occurs, "carry the one".
Here's an implementation I wrote in C:
#include <stdio.h>
//Convenience macro. Its function should be obvious.
#define swap(a,b) do { \
typeof(a) __tmp = (a); \
(a) = (b); \
(b) = __tmp; \
} while(0)
void perm_start(unsigned int n[], unsigned int count) {
unsigned int i;
for (i=0; i<count; i++)
n[i] = i;
}
//Returns 0 on wraparound
int perm_next(unsigned int n[], unsigned int count) {
unsigned int tail, i, j;
if (count <= 1)
return 0;
/* Find all terms at the end that are in reverse order.
Example: 0 3 (5 4 2 1) (i becomes 2) */
for (i=count-1; i>0 && n[i-1] >= n[i]; i--);
tail = i;
if (tail > 0) {
/* Find the last item from the tail set greater than
the last item from the head set, and swap them.
Example: 0 3* (5 4* 2 1)
Becomes: 0 4* (5 3* 2 1) */
for (j=count-1; j>tail && n[j] <= n[tail-1]; j--);
swap(n[tail-1], n[j]);
}
/* Reverse the tail set's order */
for (i=tail, j=count-1; i<j; i++, j--)
swap(n[i], n[j]);
/* If the entire list was in reverse order, tail will be zero. */
return (tail != 0);
}
int main(void)
{
#define N 3
unsigned int perm[N];
perm_start(perm, N);
do {
int i;
for (i = 0; i < N; i++)
printf("%d ", perm[i]);
printf("\n");
} while (perm_next(perm, N));
return 0;
}
Is using 1.9's Array#permutation an option?
>> a = [0,1,2].permutation(3).to_a
=> [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]
Below is my generics version of the next permutation algorithm in C# closely resembling the STL's next_permutation function (but it doesn't reverse the collection if it is the max possible permutation already, like the C++ version does)
In theory it should work with any IList<> of IComparables.
static bool NextPermutation<T>(IList<T> a) where T: IComparable
{
if (a.Count < 2) return false;
var k = a.Count-2;
while (k >= 0 && a[k].CompareTo( a[k+1]) >=0) k--;
if(k<0)return false;
var l = a.Count - 1;
while (l > k && a[l].CompareTo(a[k]) <= 0) l--;
var tmp = a[k];
a[k] = a[l];
a[l] = tmp;
var i = k + 1;
var j = a.Count - 1;
while(i<j)
{
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
i++;
j--;
}
return true;
}
And the demo/test code:
var src = "1234".ToCharArray();
do
{
Console.WriteLine(src);
}
while (NextPermutation(src));
I also came across the QuickPerm algorithm referenced in another answer. I wanted to share this answer in addition, because I saw some immediate changes one can make to write it shorter. For example, if the index array "p" is initialized slightly differently, it saves having to return the first permutation before the loop. Also, all those while-loops and if's took up a lot more room.
void permute(char* s, size_t l) {
int* p = new int[l];
for (int i = 0; i < l; i++) p[i] = i;
for (size_t i = 0; i < l; printf("%s\n", s)) {
std::swap(s[i], s[i % 2 * --p[i]]);
for (i = 1; p[i] == 0; i++) p[i] = i;
}
}
I found Joey Adams' version to be the most readable, but I couldn't port it directly to C# because of how C# handles the scoping of for-loop variables. Hence, this is a slightly tweaked version of his code:
/// <summary>
/// Performs an in-place permutation of <paramref name="values"/>, and returns if there
/// are any more permutations remaining.
/// </summary>
private static bool NextPermutation(int[] values)
{
if (values.Length == 0)
throw new ArgumentException("Cannot permutate an empty collection.");
//Find all terms at the end that are in reverse order.
// Example: 0 3 (5 4 2 1) (i becomes 2)
int tail = values.Length - 1;
while(tail > 0 && values[tail - 1] >= values[tail])
tail--;
if (tail > 0)
{
//Find the last item from the tail set greater than the last item from the head
//set, and swap them.
// Example: 0 3* (5 4* 2 1)
// Becomes: 0 4* (5 3* 2 1)
int index = values.Length - 1;
while (index > tail && values[index] <= values[tail - 1])
index--;
Swap(ref values[tail - 1], ref values[index]);
}
//Reverse the tail set's order.
int limit = (values.Length - tail) / 2;
for (int index = 0; index < limit; index++)
Swap(ref values[tail + index], ref values[values.Length - 1 - index]);
//If the entire list was in reverse order, tail will be zero.
return (tail != 0);
}
private static void Swap<T>(ref T left, ref T right)
{
T temp = left;
left = right;
right = temp;
}
Here's an implementation in C#, as an extension method:
public static IEnumerable<List<T>> Permute<T>(this IList<T> items)
{
var indexes = Enumerable.Range(0, items.Count).ToArray();
yield return indexes.Select(idx => items[idx]).ToList();
var weights = new int[items.Count];
var idxUpper = 1;
while (idxUpper < items.Count)
{
if (weights[idxUpper] < idxUpper)
{
var idxLower = idxUpper % 2 * weights[idxUpper];
var tmp = indexes[idxLower];
indexes[idxLower] = indexes[idxUpper];
indexes[idxUpper] = tmp;
yield return indexes.Select(idx => items[idx]).ToList();
weights[idxUpper]++;
idxUpper = 1;
}
else
{
weights[idxUpper] = 0;
idxUpper++;
}
}
}
And a unit test:
[TestMethod]
public void Permute()
{
var ints = new[] { 1, 2, 3 };
var orderings = ints.Permute().ToList();
Assert.AreEqual(6, orderings.Count);
AssertUtil.SequencesAreEqual(new[] { 1, 2, 3 }, orderings[0]);
AssertUtil.SequencesAreEqual(new[] { 2, 1, 3 }, orderings[1]);
AssertUtil.SequencesAreEqual(new[] { 3, 1, 2 }, orderings[2]);
AssertUtil.SequencesAreEqual(new[] { 1, 3, 2 }, orderings[3]);
AssertUtil.SequencesAreEqual(new[] { 2, 3, 1 }, orderings[4]);
AssertUtil.SequencesAreEqual(new[] { 3, 2, 1 }, orderings[5]);
}
The method AssertUtil.SequencesAreEqual is a custom test helper which can be recreated easily enough.
How about a recursive algorithm you can call iteratively? If you'd actually need that stuff as a list like that (you should clearly inline that rather than allocate a bunch of pointless memory). You could simply calculate the permutation on the fly, by its index.
Much like the permutation is carry-the-one addition re-reversing the tail (rather than reverting to 0), indexing the specific permutation value is finding the digits of a number in base n then n-1 then n-2... through each iteration.
public static <T> boolean permutation(List<T> values, int index) {
return permutation(values, values.size() - 1, index);
}
private static <T> boolean permutation(List<T> values, int n, int index) {
if ((index == 0) || (n == 0)) return (index == 0);
Collections.swap(values, n, n-(index % n));
return permutation(values,n-1,index/n);
}
The boolean returns whether your index value was out of bounds. Namely that it ran out of n values but still had remaining index left over.
And it can't get all the permutations for more than 12 objects.
12! < Integer.MAX_VALUE < 13!
-- But, it's so very very pretty. And if you do a lot of things wrong might be useful.
I have implemented the algorithm in Javascript.
var all = ["a", "b", "c"];
console.log(permute(all));
function permute(a){
var i=1,j, temp = "";
var p = [];
var n = a.length;
var output = [];
output.push(a.slice());
for(var b=0; b <= n; b++){
p[b] = b;
}
while (i < n){
p[i]--;
if(i%2 == 1){
j = p[i];
}
else{
j = 0;
}
temp = a[j];
a[j] = a[i];
a[i] = temp;
i=1;
while (p[i] === 0){
p[i] = i;
i++;
}
output.push(a.slice());
}
return output;
}
I've used the algorithms from here. The page contains a lot of useful information.
Edit: Sorry, those were recursive. uray posted the link to the iterative algorithm in his answer.
I've created a PHP example. Unless you really need to return all of the results, I would only create an iterative class like the following:
<?php
class Permutator implements Iterator
{
private $a, $n, $p, $i, $j, $k;
private $stop;
public function __construct(array $a)
{
$this->a = array_values($a);
$this->n = count($this->a);
}
public function current()
{
return $this->a;
}
public function next()
{
++$this->k;
while ($this->i < $this->n)
{
if ($this->p[$this->i] < $this->i)
{
$this->j = ($this->i % 2) * $this->p[$this->i];
$tmp = $this->a[$this->j];
$this->a[$this->j] = $this->a[$this->i];
$this->a[$this->i] = $tmp;
$this->p[$this->i]++;
$this->i = 1;
return;
}
$this->p[$this->i++] = 0;
}
$this->stop = true;
}
public function key()
{
return $this->k;
}
public function valid()
{
return !$this->stop;
}
public function rewind()
{
if ($this->n) $this->p = array_fill(0, $this->n, 0);
$this->stop = $this->n == 0;
$this->i = 1;
$this->j = 0;
$this->k = 0;
}
}
foreach (new Permutator(array(1,2,3,4,5)) as $permutation)
{
var_dump($permutation);
}
?>
Note that it treats every PHP array as an indexed array.

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);
}
}