Adobe Interview Question
Software Engineer / Developers#include<stdio.h>
#include<conio.h>
#include<algorithm>
using namespace std;
int times;
int range;
void print(int *ar)
{
static int count=0;
static int no=0;
if(count>=times)
return;
printf("%d %d %d\n",ar[0],ar[1],ar[2]);
no++;
count++;
if(no==range-1)
{
no=0;
// return;
}
swap(ar[no],ar[no+1]);
print(ar);
}
int main()
{
int ar[]={1,2,3};
times=6;
range=3;
print(ar);
getch();
}
obvoiusly here range is array_length-1 and times is 3P2
const int N = 5;
const int alphabet[N] = { 1, 2, 3, 4, 5 };
void print()
{
for (int i = 0; i < N; ++i)
std::cout << alphabet[i] << " ";
std::cout << std::endl;
}
void swap(int & x, int & y)
{
int temp = x;
x = y;
y = temp;
}
void combination(int offset = 0)
{
if (offset == N - 1)
print();
else
{
combination(offset + 1);
for (int i = offset + 1; i < N; ++i)
{
swap(alphabet[offset], alphabet[i]);
combination(offset + 1);
swap(alphabet[offset], alphabet[i]);
}
}
}
here i would like to make a distinction between permutation and combination.
given 123
all combinations are
{}
{1}
{2}
{3}
{12}
{23}
{13}
{123} totally 2^3 combinations
however all permutations are
{123} (132) {213} {231} {312}{321} total 3! permutations..
HENCE BE CAREFUL. COMBINATIONS ARE NOT ANAGRAMS
#include <stdio.h>
#include <stdlib.h>
#define MAX 4
void print(int a[],int b[])
{ int i;static int c=1;
printf("\n Combination %d :",c++);
for(i=0;i<MAX;i++)
{ if(b[i]==1)
printf("\t%d",a[i]);
}
}
void combinations(int a[],int b[],int n)
{ if(n==(MAX))
{ print(a,b);
}
else
{ b[n]=0;
combinations(a,b,n+1);
b[n]=1;
combinations(a,b,n+1);
}
}
int main()
{ int a[MAX]={1,2,3,4};int b[MAX];
combinations(a,b,0);
}
I hope this answers the question correctly
Simple recursion gving all 2^n combination
public static class Combos
{
public static void PrintAllCombos(int[] values)
{
int n = values.Length;
int[] index = new int[n];
PrintCombos(values, index, 0);
}
public static void PrintCombos(int[] values, int[] index, int pos)
{
if (pos == index.Length)
{
foreach (int i in index)
{
Console.Write(values[i]);
Console.Write(' ');
}
Console.WriteLine("\n");
return;
}
for (int i = 0; i < index.Length; i++)
{
bool occupied = false;
for (int j = 0; j < pos; j++)
{
if (index[j] == i)
occupied = true;
}
if (!occupied)
{
index[pos] = i;
PrintCombos(values, index, pos + 1);
}
}
}
}
We can use binary notations like
- DashDash July 06, 2010Let say we have 3 elements then number of combinations will be
2^3
000
001
010
011
100
101
110
111
Now replcace the 1's with numbers in that position...