Finding subsequence using bit manipulation programming questions [closed] - algorithm

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
How to approach for finding solution to subsequence and subsets problems like finding the subsequence or subsets of an array which satisfy particular condition and should be solved using bits manipulation and what is the best time complexity to which it can be reduced to.
I have started practicing a lot of coding questions these days.
Need little help.
I expect some proper approach which should be followed to solve that's kind of problems.

Count from 0 to (2set.size() - 1) (inclusive). Retrieve the elements corresponding to 1 bits in the current count. The set will have to be ordered to retrieve elements by index, of course.
The only tricky part is pulling out the elements corresponding to the 1 bits in the current count. Here's pseudocode for one way to do that:
for (int pos = 0, mask = 1; mask <= currentCount; mask <<= 1; ++pos) {
if ((currentCount & mask) != 0) {
include element at pos in the current subset
}
}
Note that this assumes that the original set size is no more than the number of bits available for whatever integer type you are using for the count and mask.
Implementation in Java will look like this:
private static void findSubsets(int array[]) {
int numOfSubsets = 1 << array.length;
for (int i = 0; i < numOfSubsets; i++) {
int pos = array.length - 1;
int bitmask = i;
System.out.print("{");
while (bitmask > 0) {
if ((bitmask & 1) == 1)
System.out.print(array[pos] + ",");
bitmask >>= 1;
pos--;
}
System.out.print("}");
}
}

Related

Algorithm to get indexes in order [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to assign indexes, in order, starting from 0, to objects. When an object is destroyed, the index should be freed for another use, eg.:
allocate_index() returns 0
allocate_index() returns 1
allocate_index() returns 2
allocate_index() returns 3
allocate_index() returns 4
release_index(1)
release_index(3)
allocate_index() returns 1
allocate_index() returns 3
allocate_index() returns 5
This is similar to allocating file descriptor in a unix with open() and releasing with close().
But there is no bound fixed in advance.
Is there an efficient algorithm/data structure for allocating/freeing those indices?
Adding to #Deimos's answer.
Only the released indices need to be stored in a heap data structure as opposed to all available indexes and use an additional variable to keep track of the currentIndex. That way if the next_index is the consecutive next and not from one of the released index it can be accessed in O(1) time as opposed to having the next_index pull from an heap of available indices and inserting back again the next available index. Both of which are O(log N) operations.
A sample code could look like this
#include <bits/stdc++.h>
class MaintainIndex
{
private:
int currentIndex;
set<int> releasedIndex;
public:
MaintainIndex()
{
currentIndex = 1;
}
MaintainIndex(int start)
{
currentIndex = start;
}
int get_index()
{
int nextIndex;
// No released indices available. Return the next consecutive one
if(releasedIndex.size() == 0)
{
nextIndex = currentIndex;
currentIndex += 1;
}
else //Return the smallest released index
{
nextIndex = *releasedIndex.begin();
releasedIndex.erase(releasedIndex.begin());
}
return nextIndex;
}
void release_index(int index)
{
releasedIndex.insert(index);
}
};
I'll go with a binary heap of available indexes. Thanks for everybody's help + downvoting + closing votes: always a pleasure to ask a question on Stakoverflow!

Returning a specific output on basis of specific set of input [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I had been asked to provide the java implementation of the following pseudo code:
function 
{
Input n; //can have either of the two values : 10 or 20
if n == 10
  return 20
  else
  return 10
}
I tried following :
int function(int n){
if (n == 10){
return 20;
}
return 10;
}
Now the next one:
int function (int n){
return n == 10 ? 20 : 10;
}
Here is another one (an extreme one-liner):
int function (int n){
return 30 - n;
}
But, the question asker had some more technique (in a single line), in his mind and I wonder what that might be!
Any idea?
You could use bit-shift operators :
return n==10?n<<1:n>>1;
or multiplication/division :
return n==10?n*2:n/2;

Algorithm to find other two sides of a trianlge when one side is given [duplicate]

This question already has answers here:
Algorithm to determine whether a given number N can become hypotenuse of right triangle with all 3 integral sides
(5 answers)
Closed 9 years ago.
There is a triangle, and its hypotenuse length is given to us. Now our task is to find whether other two sides are also integer or not.
For above question, I build one code, but that is inefficient, can you suggest any efficient algorithm for the same.
My work
#include<stdio.h>
#include<cmath>
using namespace std;
int isInt(double x) {
if( (x - (int)x) == 0 ) return 1;
return 0;
}
main() {
int S;
int flag = 0;
scanf("%d", &S);
flag = 0;
for(int i = 1; i < S; i++) {
if( isInt(sqrt(S*S - i*i)) ) {
printf("EXIST\n");
flag = 1;
break;
}
}
if(!flag) printf("NOT EXIST\n");
return 0;
}
If I understand you correctly, you are trying to answer the question "Does an integer sized right triangle with hypothenuse S exist?".
Immediate improvements to your method:
Loop i from 1 to S/2 instead of 1 to S-1.
Actually, S/2 itself is not necessary either, since that would imply a==b, and c must therefore contain an odd number of sqrt(2)-factors.
(No need to set flag=0 twice.)
Instead of checking for integer square roots (sqrt operation is time consuming), you could use this alternative integer-only variant:
int check(int c){
int a=1;
int b=c-1;
int cc=c*c;
while(a<b){
int sum=a*a+b*b;
if(sum==cc) return true;
if(sum<cc){
a++;
}else{
b--;
}
}
return false;
}
(code not tested.)
There are other ways to answer the question involving theorems for expressibility as the sum of two squares applied to the square of the given hypothenuse. However, these generally involve factorization, which is also a hard problem.
(edit: removed wrong statement regarding factorization complexity)
Further info:
http://en.wikipedia.org/wiki/Pythagorean_triple
http://en.wikipedia.org/wiki/Fermat's_theorem_on_sums_of_two_squares
(see comments, I'm not allowed to post enough links)

How can we find a repeated number in array in O(n) time and O(1) space complexity

How can we find a repeated number in array in O(n) time and O(1) complexity?
eg
array 2,1,4,3,3,10
output is 3
EDIT:
I tried in following way.
i found that if no is oddly repeated then we can achieve the result by doing xor . so i thought to make the element which is odd no repeating to even no and every evenly repeating no to odd.but for that i need to find out unique element array from input array in O(n) but couldn't find the way.
Assuming that there is an upped bound for the values of the numbers in the array (which is the case with all built-in integer types in all programming languages I 've ever used -- for example, let's say they are 32-bit integers) there is a solution that uses constant space:
Create an array of N elements, where N is the upper bound for the integer values in the input array and initialize all elements to 0 or false or some equivalent. I 'll call this the lookup array.
Loop over the input array, and use each number to index into the lookup array. If the value you find is 1 or true (etc), the current number in the input array is a duplicate.
Otherwise, set the corresponding value in the lookup array to 1 or true to remember that we have seen this particular input number.
Technically, this is O(n) time and O(1) space, and it does not destroy the input array. Practically, you would need things to be going your way to have such a program actually run (e.g. it's out of the question if talking about 64-bit integers in the input).
Without knowing more about the possible values in the array you can't.
With O(1) space requirement the fastest way is to sort the array so it's going to be at least O(n*log(n)).
Use Bit manipulation ... traverse the list in one loop.
Check if the mask is 1 by shifting the value from i.
If so print out repeated value i.
If the value is unset, set it.
*If you only want to show one repeated values once, add another integer show and set its bits as well like in the example below.
**This is in java, I'm not sure we will reach it, but you might want to also add a check using Integer.MAX_VALUE.
public static void repeated( int[] vals ) {
int mask = 0;
int show = 0;
for( int i : vals ) {
// get bit in mask
if( (( mask >> i ) & 1) == 1 &&
(( show >> i ) & 1) == 0 )
{
System.out.println( "\n\tfound: " + i );
show = show | (1 << i);
}
// set mask if not found
else
{
mask = mask | (1 << i);
System.out.println( "new: " + i );
}
System.out.println( "mask: " + mask );
}
}
This is impossible without knowing any restricted rules about the input array, either that the Memory complexity would have some dependency on the input size or that the time complexity is gonna be higher.
The 2 answers above are infact the best answers for getting near what you have asked, one's trade off is Time where the second trade off is in Memory, but you cant have it run in O(n) time and O(1) complexity in SOME UNKNOWN INPUT ARRAY.
I met the problem too and my solution is using hashMap .The python version is the following:
def findRepeatNumber(lists):
hashMap = {}
for i in xrange(len(lists)):
if lists[i] in hashMap:
return lists[i]
else:
hashMap[lists[i]]=i+1
return
It is possible only if you have a specific data. Eg all numbers are of a small range. Then you could store repeat info in the source array not affecting the whole scanning and analyzing process.
Simplified example: You know that all the numbers are smaller than 100, then you can mark repeat count for a number using extra zeroes, like put 900 instead of 9 when 9 is occurred twice.
It is easy when NumMax-NumMin
http://www.geeksforgeeks.org/find-the-maximum-repeating-number-in-ok-time/
public static string RepeatedNumber()
{
int[] input = {66, 23, 34, 0, 5, 4};
int[] indexer = {0,0,0,0,0,0}
var found = 0;
for (int i = 0; i < input.Length; i++)
{
var toFind = input[i];
for (int j = 0; j < input.Length; j++)
{
if (input[j] == toFind && (indexer[j] == 1))
{
found = input[j];
}
else if (input[j] == toFind)
{
indexer[j] = 1;
}
}
}
return $"most repeated item in the array is {found}";
}
You can do this
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main ()
{
clrscr();
int array[5],rep=0;
for(int i=1; i<=5; i++)
{
cout<<"enter elements"<<endl;
cin>>array[i];
}
for(i=1; i<=5; i++)
{
if(array[i]==array[i+1])
{
rep=array[i];
}
}
cout<<" repeat value is"<<rep;
getch();
}

calculating the number of bits using K&R method with infinite memory

I got answer for the question, counting number of sets bits from here.
How to count the number of set bits in a 32-bit integer?
long count_bits(long n) {
unsigned int c; // c accumulates the total bits set in v
for (c = 0; n; c++)
n &= n - 1; // clear the least significant bit set
return c;
}
It is simple to understand also. And found the best answer as Brian Kernighans method, posted by hoyhoy... and he adds the following at the end.
Note that this is an question used during interviews. The interviewer will add the caveat that you have "infinite memory". In that case, you basically create an array of size 232 and fill in the bit counts for the numbers at each location. Then, this function becomes O(1).
Can somebody explain how to do this ? If i have infinite memory ...
The fastest way I have ever seen to populate such an array is ...
array[0] = 0;
for (i = 1; i < NELEMENTS; i++) {
array[i] = array[i >> 1] + (i & 1);
}
Then to count the number of set bits in a given number (provided the given number is less than NELEMENTS) ...
numSetBits = array[givenNumber];
If your memory is not finite, I often see NELEMENTS set to 256 (for one byte's worth) and add the number of set bits in each byte in your integer.
int counts[MAX_LONG];
void init() {
for (int i= 0; i < MAX_LONG; i++)
{
counts[i] = count_bits[i]; // as given
}
}
int count_bits_o1(long number)
{
return counts[number];
}
You can probably pre-populate the array more wiseley, i.e. fill with zeros, then every second index add one, then every fourth index add 1, then every eighth index add 1 etc, which might be a bit faster, although I doubt it...
Also, you might account for unsigned values.

Resources