Amit Petkar
BAN USERCheck my answer as well..
- Amit Petkar March 25, 2014public class Matrix_Mirroring {
public static void displayMatrix(int[][] arr) {
for (int i = 0; i < arr[0].length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println("");
}
}
public static void matrixMirror(int [][]arr)
{
int temp = 0;
for(int i=0; i< arr.length; i++)
{
for(int j=0; j<=i-1; j++)
{
temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
}
public static void main(String[] args) {
int[][] arr = {{1, 2, 3,4}, {5, 6, 7,8}, {9, 10, 11,12},{13,14,15,16}};
displayMatrix(arr);
matrixMirror(arr);
System.out.println("---");
displayMatrix(arr);
}
}
+1 from me. Another nice logic. Only slight space complexity is increased by empty node.
- Amit Petkar March 21, 2014justify.
- Amit Petkar March 21, 2014Please elaborate with pseudo code at least.
- Amit Petkar March 12, 2014Some of the solutions provided above expects difference of 1 within nos. in a sequence. Following solution can take any sequence provided the difference between nos. is consistent (in Arithmetic progression); except with the missing value.
//test cases:
int []arr = {-20,-14,-2,4}; //gives -8 , diff of 6
int []arr = {10,30,40}; //gives 20, diff of 10
int []arr = {2,6,8,10}; //gives 4, diff of 4
public static int myFindMissing(int []arr)
{
int diff=0;
int prevDiff=Integer.MIN_VALUE;
int i=1;
for(;i<arr.length;i++)
{
diff = arr[i]-arr[i-1];
if(diff!=prevDiff)
{
if(i==2)
{
i=1;
prevDiff = diff;
break;
}
if(prevDiff==Integer.MIN_VALUE)
prevDiff=diff;
else
break;
}
}
return(arr[i-1]+prevDiff);
}
Try answering that to the interviewer..
- Amit Petkar March 12, 2014Guys, please do not expect the binary tree as balanced and height logic would not be accurate for them.
public static void ZigZagTraverser(Node root)
{
Stack<Node> stk_LR = new Stack<Node>();
Stack<Node> stk_RL = new Stack<Node>();
stk_RL.push(root);
Node temp = null;
while(!(stk_LR.isEmpty() && stk_RL.isEmpty()))
{
if(!stk_LR.isEmpty())
{
temp = stk_LR.pop();
System.out.print(temp.getValue()+"\t");
if(temp.getRight()!=null)
{
stk_RL.push(temp.getRight());
}
if(temp.getLeft()!=null)
{
stk_RL.push(temp.getLeft());
}
}
else if(!stk_RL.isEmpty())
{
temp = stk_RL.pop();
System.out.print(temp.getValue()+"\t");
if(temp.getLeft()!=null)
{
stk_LR.push(temp.getLeft());
}
if(temp.getRight()!=null)
{
stk_LR.push(temp.getRight());
}
}
}
}
Right bitwise shifting will divide given no. by power of 2. Bit shifting is definitely not the solution..
So, 100>>1 will be 100/pow(2,1) ie 100/2 = 50
100>>2 will be 100/pow(2,2) ie 100/4 = 25
Requirement clearly states that
"...any layer has lesser rocks than its base layer".
So, we are expecting the difference between no. of rocks in each layer should be atleast 1.
Also, I am not sure if arrangement with no layers above (only single layer) is valid or not.
@Heynairb... Well.. everyone has right of perceiving things.. We'll leave that to our interviewers.. :P
- Amit Petkar January 04, 2014Based on my understanding,
Expected answer for n=11 are
* 1 10
* 1 2 8
* 1 2 3 5
* 1 3 7
* 1 4 6
* 2 9
* 2 3 6
* 2 4 5
* 3 8
* 4 7
* 5 6
So count = 11
Following is my code using recursion. I've tried solutions provided above but none of them gave me proper answer... Chk the following code..
Initial Call: myMethod(0,11)
public static int myMethod(int a, int b)
{
int count = 0;
if(a<b)
{
int tmp = 0;
for(int i= (++a); ;i++)
{
tmp = b-i;
if(tmp>i)
{
count = count+1+myMethod(i,tmp);
}
else
{
break;
}
}
return count;
}
else
return 0;
}
Please justify...
- Amit Petkar January 03, 2014Please justify...
- Amit Petkar January 03, 2014@SoySauce.. What should be first input for your method?
- Amit Petkar January 03, 2014@Vikimanish... We could have expressions as :
P=30 (Set pressure to 30 PSI)
S=10 (Set speed to 10) n so on.
At the start of system, we could assume those values as 0.
And as far as "user-friendly" is concerned, it is the expected requirement; so cannot help it.
I am assuming that it would be expecting expressions say:
P+30 (exceed pressure by 30 P)
S-10 (reduce speed by 10) and so on...
@Aravind..
Could you explain your logic based on sample output provided. Please edit the code that suits your logic and comment here.
What I understood from this question is as follows:
For a given nxn matrix(array), the value A[i][j] represents value in ith row and jth column. Now, c and d (from A(c,d)) are to considered in such a way that their values should be greater than a and b (from A(a,b)) respectively. So, we can conclude that values of a and b cannot be equal to n( n-1 since arrays are zero indexed). Also, the values of c and d should be at least greater than a and b respectively by 1. So, considering these facts, I created following logic:
public static void max(int [][]arr)
{
int max = Integer.MIN_VALUE;
int n = arr.length;
int temp=0;
for(int a=0; a<(n-1); a++)
{
for(int b=0; b<(n-1); b++)
{
for(int c=a+1; c<n;c++)
{
for(int d=b+1; d<n;d++)
{
//System.out.println(a+" "+b+" "+c+" "+d+": value:"+(arr[c][d]-arr[a][b]));
if(max<(arr[c][d]-arr[a][b]))
max = arr[c][d]-arr[a][b];
}
}
}
}
System.out.println("Max:"+max);
}
Sample output for your reference:
Matrix input:
14 17 65
79 27 22
71 62 16
0 0 1 1: value:13
0 0 1 2: value:8
0 0 2 1: value:48
0 0 2 2: value:2
0 1 1 2: value:5
0 1 2 2: value:-1
1 0 2 1: value:-17
1 0 2 2: value:-63
1 1 2 2: value:-11
Max:48
Please suggest me if this code can be improvised further. Though it may seem that the complexity is worse than O(n^2), these iterations would only pic valid combinations only.
- Amit Petkar October 07, 2013Initially, we will get count of rows and columns. min (row count,col count) would be the maximum (and possibly optimised) no. of moves possible.
Now, we get the no. of demons across rows and columns and get the row no. (or col no.) having the max no. of demons in it. Once we get the row no. (or col. no), we can attack across that path and clear all the values (demons) on the path (row or col). Once done, we again need to get the no. of demons across rows and columns after attack and get the row (or col) no having max no. of demons. This has to be repeated till all demons are cleared.
We need to maintain the count of attacks made. If no. of attacks made is less than min(row count, col count) then that is the optimised no. of attacks possible OR else min(row count, col count) is the final answer.
I believe this solution should work. Working on this to further optimize this approach and code. Any suggestions welcome.
@Nini,
If you observe the code "o.getClass().getMethod(property, new Class[] {})", property states the getter method name of the class considered. So, consider Student class as follows:
public class Student
{
private String name;
Student(){}
Student(String name) {this.name = name;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
}
"o.getClass().getMethod(getName, new Class[] {})" would get "getName" method on current object i.e. Student. And ".invoke(o, new Class[] {})" would invoke the same which would return String which can be saved in Object variable and later typecasted as Comparable.
- Amit Petkar October 04, 2013Dear Ghosh,
Comparison makes sense if given two objects are mutually comparable. Comparator expects such objects. Read javadoc of Comparator interface.
How are you intending to compare objects and sort a list which comprises String, Integer and some other Javabean say Student.
Nice code Pani.. :)
However; your code would not be able to handle basic types like String, Integers etc. So, you could replace getComparable() code as follows:
private Comparable getComparable(Object o) {
try {
if(!(o instanceof Comparable))
{
Object invoke = o.getClass().getMethod(property, new Class[] {})
.invoke(o, new Class[] {});
return ((Comparable)invoke);
}
else
{
return (Comparable)o;
}
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage());
}
}
Is there any scope to improvise this code.. Suggestions are welcome.
- Amit Petkar October 01, 2013Use reflections...
This code is written under following assumptions:
> The objects to be compared should conform to JavaBean Conventions (should have getter methods atleast to all fields to be compared with)
> Currently would be able to handle basic types like String, int and float only (need to add code to handle all comparable types). I am unable to generalise the code to handle all Comparable types. Would appreciate if someone come with the solution for the same.
> I know my code is very crude. Would appreciate if someone would improvise this code that would comply with ethical coding conventions. Also, I believe implementing generics may help. I am unable to come up with that solution though.
> This code is currently comparing all the available field in JavaBean
public class AllComparator implements Comparator<Object> {
public static boolean isGetter(Method method) {
if (!method.getName().startsWith("get")) {
return false;
}
if (method.getParameterTypes().length != 0) {
return false;
}
if (void.class.equals(method.getReturnType())) {
return false;
}
return true;
}
@Override
public int compare(Object o1, Object o2) {
if (o1.getClass().toString().equals("class java.lang.String")) {
return ((String) o1).compareTo((String) o2);
} else if (o1.getClass().toString().equals("class java.lang.Integer")) {
return ((Integer) o1).compareTo((Integer) o2);
} else if (o1.getClass().toString().equals("class java.lang.Float")) {
return ((Float) o1).compareTo((Float) o2);
} else {
Method[] methods = o1.getClass().getMethods();
int greater = 0;
int lesser = 0;
int equals = 0;
int result = 0;
String retType = null;
for (Method method : methods) {
if (isGetter(method)) {
Object obj1 = null, obj2 = null;
try {
obj1 = method.invoke(o1);
obj2 = method.invoke(o2);
} catch (Exception ex) {
ex.printStackTrace();
}
retType = method.getReturnType().toString();
if (retType.equals("float")) {
// try{
float x = Float.parseFloat(obj1.toString());
float y = Float.parseFloat(obj2.toString());
result = (x > y) ? 1 : (x == y) ? 0 : (-1);
if (result > 0) {
greater++;
}
if (result < 0) {
lesser++;
}
if (result == 0) {
equals++;
}
} else if (retType.equals("int")) {
int x = Integer.parseInt(obj1.toString());
int y = Integer.parseInt(obj2.toString());
result = (x > y) ? 1 : (x == y) ? 0 : (-1);
if (result > 0) {
greater++;
}
if (result < 0) {
lesser++;
}
if (result == 0) {
equals++;
}
} else if (retType.equals("class java.lang.String")) {
String x = obj1.toString();
String y = obj2.toString();
result = x.compareTo(y);
if (result > 0) {
greater++;
}
if (result < 0) {
lesser++;
}
if (result == 0) {
equals++;
}
}
}
}
if (lesser > greater) {
if (lesser > equals) {
return -1;
} else {
return 0;
}
} else {
if (greater > equals) {
return 1;
} else {
return 0;
}
}
}
}
}
class Bean001 {
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public float getC() {
return c;
}
public void setC(float c) {
this.c = c;
}
private int a;
private String b;
private float c;
}
public class AllComparatorTester {
public static void main(String[] args) {
ArrayList al = new ArrayList();
Bean001 b1 = new Bean001();
b1.setA(2);
b1.setB("b");
b1.setC(3.14f);
al.add(b1);
// al.add(2);
Bean001 b2 = new Bean001();
b2.setA(1);
b2.setB("a");
b2.setC(1.5f);
al.add(b2);
// al.add(1);
// System.out.println("arrayList before sorting.." + al);
// java.util.Collections.sort(al, new AllComparator());
// System.out.println("arrayList after sorting.." + al);
Bean001 x;
System.out.println("arrayList before sorting..");
for (Object o : al) {
x = (Bean001) o;
System.out.println(x.getA() + " " + x.getB() + " " + x.getC());
}
System.out.println("After sorting...");
java.util.Collections.sort(al, new AllComparator());
for (Object o : al) {
x = (Bean001) o;
System.out.println(x.getA() + " " + x.getB() + " " + x.getC());
}
}
}
public class Tester004 {
public static void main(String[] args) {
int limit=5;
char c='a';
go(0,limit,c);
}
public static void go(int i,int limit, char c) {
if (i < limit) {
System.out.println(c);
i++;
go2(i,limit,c);
}
}
public static void go2(int i,int limit, char c) {
if (i < limit) {
System.out.println(c);
i++;
go(i,limit,c);
}
}
}
This logic doesnt work. Please clarify your approach.
Also, check link provided by nik below. The approach is awesome.
public int falling_Disks(int rings[], int disks[])
{
int rings_length= rings.length;
int count = 0;
for(int disk: disks)
{
for(int i=0; i<rings_length; i++)
{
if(disk<=rings[i]) //if disk can go through the ring
{
if(i!=rings_length-1)
continue;
else //if disk has reached the end of well
{
++count;
rings_length=i;
break;
}
}
else //if disk get stuck
{
if(i==0) //if disk get stuck at first ring itself
{
rings_length=0;
break;
}
else
{
++count;
rings_length=i-1;
break;
}
}
}
if(rings_length==0) //if well is full, no need to lookup for disks
break;
}
return count;
}
This code is under assumption made in solution by ibnipun10 dated August 10, 2010.
//Initial call: printTreesColumns(tree.getRoot());
- Amit Petkar March 31, 2014