scgupta
BAN USER
- 0of 0 votes
AnswersImplement following interface so that multi-put is atomic. Expect multiple producers and consumers inserting to and extracting from this queue implementation.
- scgupta in India
/**
* threadSafe bounded blocking queue implementation. Expected to be used in a
* Producer->Consumer pattern
*/
public interface MultiPutBlockingBoundedQueue<E> {
/**
* Sets the capacity of the buffer. Can be called only once. If called more
* than once or if the passed capacity is <= 0, throw an exception.
*/
public void init(int capacity) throws Exception;
/**
* Get the next item from the queue throws Exception if not initialized
*/
public E get() throws Exception;
/**
* Put the item to the tail of the queue. throws Exception if not
* initialized
*/
public void put(E obj) throws Exception;
/**
* Put the list of items in an atomic manner. The list can be more than the
* capacity throws Exception if not initialized
*/
public void multiput(List<E> objs) throws Exception;
}| Report Duplicate | Flag | PURGE
Linkedin Software Engineer Java
public class Number {
private enum State {
INIT, SIGN, INTEGER, DOT, FRACTION
}
public static boolean isNumber(String str) {
// RegEx: [+-]? [0-9]+ (\.[0-9]+)?
State state = State.INIT;
for (final char ch : str.trim().toCharArray()) {
switch (state) {
case INIT:
if (ch == '+' || ch == '-') {
state = State.SIGN;
} else if (ch >= '0' && ch <= '9') {
state = State.INTEGER;
} else {
return false;
}
break;
case SIGN:
if (ch >= '0' && ch <= '9') {
state = State.INTEGER;
} else {
return false;
}
break;
case INTEGER:
if (ch == '.') {
state = State.DOT;
} else if (ch < '0' || ch > '9') {
return false;
}
break;
case DOT:
if (ch >= '0' && ch <= '9') {
state = State.FRACTION;
} else {
return false;
}
break;
case FRACTION:
if (ch < '0' || ch > '9') {
return false;
}
break;
}
}
return (state == State.INTEGER || state == State.FRACTION);
}
public static void main(String[] args) {
final String str[] = { "1", "10", "0123", "-20", "+40", ";", "10.", "-", "-23.45" };
for (final String s : str) {
System.out.println("Test: \"" + s + "\" is" + ((Number.isNumber(s)) ? " " : " not ") + "a number");
}
}
}
import java.util.Arrays;
public class TriangleTriplets {
public static int countTriangleTriplets(int[] array) {
int count = 0;
Arrays.sort(array);
for (int i = 0; i < array.length - 2; i++) {
int k = i + 2;
for (int j = i + 1; j < array.length - 1; j++) {
int maxAllowed = array[i] + array[j];
while (k < array.length && array[k] < maxAllowed) {
k++;
}
count += k - j - 1;
// DEBUG
//for (int l = j + 1; l < k; l++) {
// System.out.println("" + array[i] + ", " + array[j] + ", " + array[l]);
//}
}
}
return count;
}
public static void main(String[] args) {
System.out.println("Total trangle triplets : " + countTriangleTriplets(new int[0]));
System.out.println("Total trangle triplets : " + countTriangleTriplets(new int[] { 1, 1, 10000 }));
System.out.println("Total trangle triplets : "
+ countTriangleTriplets(new int[] { 10, 21, 22, 100, 101, 200, 300 }));
System.out.println("Total trangle triplets : " + countTriangleTriplets(new int[] { 9, 8, 10, 7 }));
}
}
public class BinarySearch {
public static int binarySearch(final int[] array, final int value) {
return binarySearchHelper(array, value, 0, array.length - 1);
}
private static int binarySearchHelper(final int[] array,
final int value, final int left, final int right) {
if (left > right)
return -1; // not found
int mid = (left + right) / 2;
if (value == array[mid]) {
return mid;
} else if (value < array[mid]) {
return binarySearchHelper(array, value, left, mid - 1);
} else { // (value > array[mid])
return binarySearchHelper(array, value, mid + 1, right);
}
}
public static int binarySearchShifted(final int[] array, final int value) {
return binarySearchShiftedHelper(array, value, 0, array.length - 1);
}
private static int binarySearchShiftedHelper(final int[] array,
final int value, final int left, final int right) {
if (left > right)
return -1; // not found
int mid = (left + right) / 2;
if (value == array[mid]) {
return mid;
} else if ((array[left] <= array[mid] && (array[left] <= value && value < array[mid]))
|| (array[mid] <= array[right] && !(array[mid] < value && value <= array[right]))) {
return binarySearchShiftedHelper(array, value, left, mid - 1);
} else {
return binarySearchShiftedHelper(array, value, mid + 1, right);
}
}
public static void main(String[] args) {
test(6);
test(7);
}
private static void test(int count) {
int array[] = new int[count]; // {10, 20, ... 10*COUNT}
for (int i=0; i<count; i++) {
array[i] = 10 * (i+1);
}
int VALUE_MIN = 8;
int VALUE_MAX = 10 * count + 2;
printArray(array);
for (int value = VALUE_MIN; value <= VALUE_MAX; value++) {
int index = binarySearch(array, value);
boolean pass = ((index >= 0 && (value % 10 == 0)) || (index < 0 && (value % 10 != 0)));
if (!pass) {
System.out
.println("*** FAIL ***"
+ " value = "
+ value
+ ((index >= 0) ? (" index = " + index)
: " Not Found"));
}
}
System.out.println();
for (int shift = 0; shift < count; shift++) {
for (int i = 0; i < count; i++) {
array[i] = 10 * (((shift + i) % count) + 1);
}
printArray(array);
for (int value = VALUE_MIN; value <= VALUE_MAX; value++) {
int index = binarySearchShifted(array, value);
boolean pass = ((index >= 0 && (value % 10 == 0)) || (index < 0 && (value % 10 != 0)));
if (!pass) {
System.out.println("*** FAIL ***"
+ " value = "
+ value
+ ((index >= 0) ? (" index = " + index)
: " Not Found"));
}
}
System.out.println();
}
}
private static void printArray(int[] array) {
System.out.print("array[] = { ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
System.out.print(" ");
}
System.out.println("}");
}
}
import java.util.EmptyStackException;
import java.util.Stack;
public class Calculator {
public static void main(String[] args) {
System.out.println("Value: " + evaluateReversePolish(args));
}
public static double evaluateReversePolish(String expression) {
String[] tokens = expression.split("\\s");
return evaluateReversePolish(tokens);
}
public static double evaluateReversePolish(String[] tokens) {
Stack<Double> operands = new Stack<Double>();
for (String token : tokens) {
char ch = token.charAt(0);
if (ch >= '0' && ch <= '9') {
double operand = Double.parseDouble(token);
operands.push(operand);
} else { // Operator
Operator op = Operator.parse(token);
if (op == null) {
throw new RuntimeException(
"Malformed Expression: Unknown Operator " + token);
}
Double op1, op2;
try {
op2 = operands.pop();
op1 = operands.pop();
} catch (EmptyStackException e) {
throw new RuntimeException(
"Malformed Expression: Not enough operand for operator '"
+ op.getValue() + "'", e);
}
operands.push(op.apply(op1, op2));
}
}
if (operands.size() != 1) {
throw new RuntimeException(
"Malformed Expression: not enough opetrators");
} else {
return operands.pop();
}
}
public enum Operator {
PLUS("+") {
@Override
public double apply(double x, double y) {
return x + y;
}
},
MINUS("-") {
@Override
public double apply(double x, double y) {
return x - y;
}
},
MULT("*") {
@Override
public double apply(double x, double y) {
return x * y;
}
},
DIVIDE("/") {
@Override
public double apply(double x, double y) {
return x / y;
}
};
private final String value;
public static Operator parse(String value) {
if (value.length() != 1)
return null;
char ch = value.charAt(0);
switch (ch) {
case '+':
return PLUS;
case '-':
return MINUS;
case '*':
return MULT;
case '/':
return DIVIDE;
default:
return null;
}
}
private Operator(final String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
@Override
public String toString() {
return this.name();
}
public abstract double apply(double x, double y);
}
}
Looked like a simplified version of java.util.concurrent.ArrayBlockingQueue which implements java.util.concurrent.BlockingQueue will suffice. Except there is a twist of multi-put that must be atomic.
Here is an ad-hoc test driver to test (note that driver will hang at the end, because consumer threads will be blocked for producers to insert more elements, but producer threads would have ended):
- scgupta January 31, 2016