TATA Consultancy Services Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Written Test
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <bitset>
using namespace std;
string insert_spaces(string x, string y){
int i;
string result;
for(i=0;i<x.length();i++){
result += x[i];
if(y[i]!='0'){
result += "_";
}
}
return result;
}
int main(){
int i;
string bitcode;
for(i=0;i<8;i++){
bitset<3> x(i);
bitcode = x.to_string();
bitcode += '0';
cout << insert_spaces("abcd",bitcode) << endl;
}
}
#include <iostream>
#include <string>
#include <list>
#include <conio.h>
using namespace std;
list<string> insert_spaces(string str)
{
list<string> result;
string temp;
for(unsigned int i = 1; i < 2 << str.size() - 2; i++)
{
int f = i, j = 1;
temp = str;
while(f != 0)
{
if(f % 2 == 1)
temp.insert(j++, "_");
f /= 2;
++j;
}
result.push_back(temp);
temp.clear();
}
return result;
}
int main()
{
list<string> string_list = insert_spaces("abcd");
for( list<string>::iterator i = string_list.begin(); i != string_list.end(); i++)
{
cout << *i << endl;
}
_getch();
return 0;
}
it returns all the string combinations in form of array.
public static string[] string_combinations(string s)
{
//points to main array index
int index = 0;
//Create an array length of n(n+1)/2
string[] combiArray = new string[(s.Length * (s.Length + 1))/2];
combiArray[index++] = s;
for (int i = 1; i < s.Length; i++)
{
//recursive call on remaining string
//eg: if s = abcd and i = 1 recursive call of (bcd)
//i = 2 recursive call of (cd)
//i = 3 recursive call of (d)
string[] subCombinations = string_combinations(s.Substring(i));
foreach (string item in subCombinations)
{
if(item != null)
combiArray[index++] = s.Substring(0,i) + "_" + item;
}
}
return combiArray;
}
- Adrian Garcia August 04, 2014