kapilraju
BAN USER- 0of 0 votes
AnswersDesign a Thread safe Array Based queue with a fixed size.
- kapilraju
The behavior should be in such a way that if multiple threads are accessing the same queue and if the queue is full the threads will wait for their turn and if some other threads removes elements from queue, the waiting threads will get a chance to add elements.| Report Duplicate | Flag | PURGE
Adobe Developer Program Engineer Coding
Here is my version of code. Let me know any flaw in my way of designing the queue.
public class Queue {
private Boolean isFull;
private Integer size;
private Integer[] arr;
public Queue(Integer size) {
this.size = size;
arr = new Integer[size];
isFull = false;
}
public synchronized void add(Integer value) throws InterruptedException
{
if(isFull) this.wait();
int i = 0;
for (; i < size; i++) {
if(arr[i] == null)
{
arr[i] = value;
break;
}
}
if(i+1==size) isFull = true;
}
public synchronized Integer remove()
{
Integer firstElement = arr[0];
for (int i = 0; i < size; i++) {
if(i==size-1)
{
arr[i] = null;
}else
{
arr[i] = arr[i+1];
}
}
if(isFull)
{
isFull = false;
this.notify();
}
return firstElement;
}
@Override
public String toString() {
StringBuilder s = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
if(arr[i] != null)
s.append(arr[i]+", ");
}
return s.toString();
}
public static void main(String[] args) {
Queue queue = new Queue(5);
for (int i = 0; i < 10; i++) {
new Thread(new AddThread(queue)).start();
try {
TimeUnit.SECONDS.sleep(2);
System.out.println(queue);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 10; i++) {
new Thread(new RemoveThread(queue)).start();
try {
TimeUnit.SECONDS.sleep(2);
System.out.println(queue);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Here is my version of code, Please suggest if anyone has a better approach -
public static void main(String[] args) {
String input = "abc";
int length = input.length();
StringBuilder str = new StringBuilder();
for (int i = 0; i < length; i++) {
for (int j = 0; j < i+1; j++) {
str.append(input.charAt(i));
}
}
System.out.println(str.toString()+str.reverse().toString());
}
Solution in java-
Take an array R of size 26.
Loop through each character of the string and increment the index of R for that character.
If a string is palindrome then the count of each character in R %2 will give 0 and if string length is odd then except one character rest of character's count %2 will be 0.
Now, if you want to calculate k-palindrom add the k to the comparison as shown below.
- kapilraju January 15, 2014