Algorithm to get indexes in order [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 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!

Related

reverse a stack using an auxiliary stack, but the original stack to be returned [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 3 days ago.
Improve this question
To reverse and return the original queue using an auxiliary queue is easy to do, but for the stack, to reverse and return the original one using an auxiliary one is easily doable with the help of a variable?
The only way I see this working is by using recursion, but to me this is like cheating, you could as well read the data in an array and reverse it. The code is pretty simple, to copy a stack you do the same as when reversing a list recursively, but because the elements in a stack are iterated in reverse order already when popping them, you create the original stack and not a reverse.
function move(from, to) {
const v = from.pop()
if (v !== undefined) {
move(from, to)
// from.push(v) // uncomment this to make it copy instead of move
to.push(v)
}
}
function reverse(stack) {
const aux = [] // aux stack
move(stack, aux)
let v = aux.pop()
while (v !== undefined) {
stack.push(v)
v = aux.pop()
}
}
const s = [0,1,2,3]
console.log(s)
reverse(s)
console.log(s)
Or here the (very evil and potentially failing) solution without recursion and aux (in other words, the rules have to be specified more clearly):
function reverse(stack, callback) {
let delay = 10
setTimeout(callback, stack.length * 10 + 10)
let v = stack.pop()
while (v !== undefined) {
(function(v, delay){setTimeout(() => stack.push(v), delay)})(v, delay)
delay += 10
v = stack.pop()
}
}
const s = [0,1,2]
reverse(s, () => console.log(s))

A algorithm problem of complete two binary tree [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 4 years ago.
Improve this question
A complete binary tree with a maximum depth of 16 is known, with all leaf nodes having the same depth. If a small ball is placed at the root node, the ball will begin to fall along the root node. There is a switch on each node in the complete binary tree. The default is all off. When the ball falls, the state of the switch changes whenever a ball falls on a switch. When the ball reaches a node, if the switch on the node is closed, go to the left to go to the ball, otherwise go to the right until it reaches the leaf node. Please help me find the leaf node number after the 12345th ball fell.
You can simulate the given problem and notice that the leaf node at which the ball ends tends to repeat itself after a point of time. For example, for a binary tree of depth 3, the leaf nodes at which the ball ends for multiple roll of the balls are 1 3 2 4 1 3 2 4 1 3 2 4 . . . (assuming the leaf nodes are numbered starting from 1). As visible, the sequence of length 23-1 = 4 keeps repeating itself. We can store this sequence in an array and answer the query for any nth ball throw by looking up the entry corresponding to the n mod 2depth-1 index in this array.
Since our depth is upto 16, the total number of operations required to generate the recurring sequence is 216-1 * 16 = 524288 operations.
Sharing the code for the same https://ideone.com/uuNV2g
#include <iostream>
#include <map>
#include <vector>
using namespace std;
map<int, bool> states; // default value is False
int MAX_DEPTH = 16;
int dfs(int cur, int depth = 0) {
if(depth == MAX_DEPTH) {
return cur - (1<<MAX_DEPTH) + 1;
}
if(states[cur] == 0) {
states[cur] = !states[cur];
return dfs(2*cur, depth+1);
}
else {
states[cur] = !states[cur];
return dfs(2*cur+1, depth+1);
}
}
int main() {
int until = (1LL<<(MAX_DEPTH-1));
vector<int> pos; // 0 indexed
for(int i = 1; i <= until; i++) {
// cout << dfs(1) << ' ';
pos.push_back(dfs(1));
}
cout << pos[(12344%until)];
// 12344 instead of 12345 since the sequence is 0 indexed
}
Hope it works out.

Finding subsequence using bit manipulation programming questions [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 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("}");
}
}

Implement "24 hour time" using an array of numbers [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 was recently given a question in an exam.
I will be given an array of 4 numbers and using that I have to construct the largest possible 24 hour time format.
For eg : If the input array is [1,3,5,2] the answer would be "23:51".
If the input array is [1,1,5,0] the answer would be "15:10".
I tried doing and did succeed but it was very rudimentary. I basically had to make 4 different arrays for each position of the time and compare with the input array.
A different approach with an implementation in any language(c, c#, objC or anything etc) would be of great help. I cant seem to get my head around my logic.
Just want to share a working solution. Not necessarily efficient.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) throws Exception {
int[] input = {1,2,6,7};
System.out.println(getLargestTime(input)+" is the largest time!");
}
public static String getLargestTime(int[] input) {
String largestTime = "00:00";
String str = input[0]+""+input[1]+""+input[2]+""+input[3];
List<String> times = new ArrayList<>();
permutation(str, times);
Collections.sort(times, Collections.reverseOrder());
for (String t: times) {
int hours = Integer.parseInt(t) / 100;
int minutes = Integer.parseInt(t) % 100;
if (hours < 24 && minutes < 60) {
if (hours < 10 && minutes < 10) {
largestTime = "0"+hours+":0"+minutes;
} else if (hours < 10) {
largestTime = "0"+hours+":"+minutes;
} else if (minutes < 10) {
largestTime = hours+":0"+minutes;
} else {
largestTime = hours+":"+minutes;
}
}
}
return largestTime;
}
public static void permutation(String str, List<String> list) {
permutation("", str, list);
}
private static void permutation(String prefix, String str, List<String> list) {
int n = str.length();
if (n == 0) list.add(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n), list);
}
}
}
Find the largest number
Place that number in the front if it is legal (0, 1, or 2 in the first spot). If it isnt, find the biggest legal number and place it first.
Repeat 1-2 with second, third, etc. largest number until a legal number is found for front
Repeat 1-3 for second to front, second to last, and last
If you end up with illegal numbers at the end, then swap those illegal numbers with the earlier number that produces the latest time.
Since there are only 4 numbers, I would generate all possible time stamps (that would be 4! i.e. 24), sort them, and find the largest valid time stamp.
How to check if t is valid 24 hour time stamp?
t is max 4 digits, i.e. t mod 10000 == 0
the last two digits (t mod 100) is a valid minute value, i.e. in the range [0-59]
the first two digits (t div 100) is a valid hour value, i.e. in the range [0-23]
It's not the complete answer, just the complement part for #arun.
For checking the valid time stamp, I assume the form of time stamp is ab:cd where a, b, c, d is the digits.
a should be from 0 to 2
If a smaller than 2, the b is all valid.
Otherwise, b should be from 0 to 3
c should be from 0 to 5
d is all valid
You can use these constraints:
To check valid time stamps after generated
OR
Use them to generate

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;

Resources