Tuesday, June 4, 2013

HackerRank: Bot saves princess

Here is the link of the question : Click Here

Download Code: Click Here
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
/* Head ends here */
static void displayPathtoPrincess(int n, String [] grid){
int pos=0;

// System.out.println("n= "+n+" S length = "+grid[1]);
String newArray[] = new String[n*n];
//System.out.println(grid.length);
/*for(int j=0;j{
System.out.println(grid[j]);
}*/
//System.out.println("---------------");
for(int i=0,k=0;i{
for(int j=0;j {
newArray[k] = ""+grid[i].charAt(j);
// System.out.println(grid[i]);
k++;
}
}
// for(int i =0;i // System.out.println(i+" "+newArray[i]);
if(newArray[0].equals("p"))
pos = 0;
else if(newArray[n-1].equals("p"))
pos = n-1;
else if(newArray[n*(n-1)].equals("p"))
pos = n*(n-1);
else if(newArray[n*(n-1) + (n-1)].equals("p"))
pos = (n*(n-1) + (n-1));

int m = ((n*n)+1)/2 -1 ;


m = (n+1)/2;
if(pos==0)
{
for(int i=0;i {
System.out.println("LEFT");
}
for(int i=0;i {
System.out.println("UP");
}
}
if(pos==n-1)
{
for(int i=0;i {
System.out.println("RIGHT");
}

for(int i=0;i {
System.out.println("UP");
}
}
if(pos==n*(n-1))
{
for(int i=0;i {
System.out.println("LEFT");
}

for(int i=0;i {
System.out.println("DOWN");
}
}
if(pos==(n*(n-1) + (n-1)))
{
for(int i=0;i {
System.out.println("RIGHT");
}

for(int i=0;i {
System.out.println("DOWN");
}
}
}
/* Tail starts here */
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m;
m = in.nextInt();
String grid[] = new String[m];
for(int i = 0; i < m; i++) {
grid[i] = in.next();
}

displayPathtoPrincess(m,grid);
}
}


Download Code: Click Here

TechGig Solution - May Edition 2013 - Easy Level - Partition Problem

Partition Problem:
Hi,
I am providing the solution of Partition Problem here. My score in the contest is 100 in java, if you have any better solution of this problem, feel free to share it.

Download Link : Code
Download link : Code
public class Partition {

/**
* @param args
*/
public static final String yes = "Yes";
public static final String no = "No";
public static final String invalid = "Invalid";
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[] = {1, 5, 11,5};

System.out.println(findPartiion(arr,4));

}
// A utility function that returns true if there is a subset of arr[]
// with sun equal to given sum
public static boolean isSubsetSum (int arr[], int n, int sum)
{
System.out.println(n+" "+sum);
// Base Cases
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;

// If last element is greater than sum, then ignore it
if (arr[n-1] > sum)
return isSubsetSum (arr, n-1, sum);

/* else, check if sum can be obtained by any of the following
(a) including the last element
(b) excluding the last element
*/
return isSubsetSum (arr, n-1, sum) || isSubsetSum (arr, n-1, sum-arr[n-1]);
}

// Returns true if arr[] can be partitioned in two subsets of
// equal sum, otherwise false
public static String findPartiion (int arr[], int n)
{
// Calculate sum of the elements in array
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += arr[i];
if(arr[i]<0)
return invalid;
}
// If sum is odd, there cannot be two subsets with equal sum
if (sum%2 != 0)
return no;

// Find if there is subset with sum equal to half of total sum
boolean b = isSubsetSum (arr, n, sum/2);
if(b)
return yes;
else
return no;

}

}


Download Link : Code
Download link : Code

Thursday, May 9, 2013

Techgig: Visit a Colony

Techgig: Visit a Colony
To view this question : Click Here

I have given the solution here, My score in the contest is 100. If you have any solution better than this feel free to share it.

Download Code: Click Here or Click Here

import java.io.*;
public class CandidateCode
{
public static int house_condition(int[] input1,int input2)
{
//Write code here
//Write code here

int houseScore[] = input1;
int houseNo = input2;
char good = 'G';

char bad = 'B';

char houseCondition[] = new char[houseScore.length];

if(input1.length==0)
return -1;
if(houseScore.length==1)
{
if(houseScore[0]==1)
return 1;
else if(houseScore[0]==0)
return -1;
else if(houseScore[0]==2 || houseScore[0]==3)
return -1;
}
else
{
for(int i=0;i{

if(i==0)
{
houseCondition[0]=good;
if(houseScore[i]==1)
houseCondition[i+1]=bad;

if(houseScore[i]==2)
houseCondition[i+1]=good;

if(houseScore[i]==3)
return -1;
continue;
} // END-IF (For first value in an array)

if(i==houseScore.length-1)
{
if(houseCondition[i]==good)
{
if(houseScore[i]==0)
{
return -1;
}
if(houseScore[i]==1)
{
if(houseCondition[i-1]==good)
return -1;
}
if(houseScore[i]==2)
{
if(houseCondition[i-1]==bad)
return -1;
}
if(houseScore[i]==3)
return -1;
}

if(houseCondition[i]==bad)
{
if(houseScore[i]==0)
{
if(houseCondition[i-1]==good)
return -1;
}
if(houseScore[i]==1)
{
if(houseCondition[i-1]==bad)
return -1;
}
if(houseScore[i]==2 || houseScore[i]==3)
return -1;
}
} // END -IF (When i is at last position)


else
{
if(houseCondition[i]==good)
{
if(houseScore[i]==3)
{
if(houseCondition[i-1]==bad)
return -1;
else
houseCondition[i+1]=good;
}

if(houseScore[i]==2)
{
if(houseCondition[i-1]==good)
houseCondition[i+1]=bad;
else
houseCondition[i+1]=good;
}
if(houseScore[i]==1)
{
if(houseCondition[i-1]==good)
return -1;
else
houseCondition[i+1]=bad;
}
if(houseScore[i]==0)
{
return -1;
}
}

if(houseCondition[i]==bad)
{
if(houseScore[i]==3)
return -1;

if(houseScore[i]==2)
{
if(houseCondition[i-1]==bad)
return -1;

else
houseCondition[i+1]=good;
}

if(houseScore[i]==1)
{
if(houseCondition[i-1]==bad)
houseCondition[i+1]=good;

else
houseCondition[i+1]=bad;
}
if(houseScore[i]==0)
{
if(houseCondition[i-1]==good)
return -1;
else
houseCondition[i+1]=bad;
}
}
}
}
}

if(houseCondition[houseNo-1]==good)
return 1;
else
return 0;
}
}



Download Code: Click Here or Click Here

Thursday, April 25, 2013

TechGig Solution: Crossing the river

Crossing the river:
Here is link of the question

I started with score of 10 then i stuck at 80 and 90 and finally i got score of 100. Here is my solution if you have better solution please share with us.

Download the below Code: Click Here

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;



public class CrossingRiver {

private static int previousMax;

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String input[] = {""};
System.out.println(bridge(input));
}

@SuppressWarnings("unchecked")
public static int bridge(String[] input1)
{
System.out.println(input1.length);
if(input1.length==0)
return 0;
int arr[];

arr=new int[2*input1.length];
StringTokenizer st;
for(int i=0,j=0;i {
st = new StringTokenizer(input1[i],"#");
while(st.hasMoreElements())
{
arr[j] = Integer.valueOf((String)st.nextElement());
j++;
}

}
for(int j:arr)
System.out.println(j);

Set set = new HashSet();
for(int j=0;j {
boolean b = set.add(arr[j]);
if(b==false)
return -1;
}
set.clear();
for(int j=1;j {
boolean b = set.add(arr[j]);
if(b==false)
return -1;
}


if(input1.length==1)
{
if(input1[0].equals(""))
return 0;

return 1;
}
else
{
int cityFirst;
int citySecond;
int cityFirstInside;
int citySecondInside;
int start;
int end;
int previous1;
boolean flag=false;
int max=0;

ArrayList al = new ArrayList();

for(int i=0;i {
cityFirst = arr[i];
citySecond = arr[i+1];
previous1 = citySecond;

for(int j=0;j {
cityFirstInside = arr[j];
citySecondInside = arr[j+1];
//1#2,2#3,3#1,4#4,5#7,6#5,7#6

if(cityFirst==cityFirstInside && citySecond==citySecondInside)
{
System.out.println("--------------------"+cityFirst+"----"+cityFirstInside+"------------");
max++;
}

else if(cityFirstInside>cityFirst)
{

if(previous1 {
max++;
System.out.println("happy"+cityFirstInside);
previous1=citySecondInside;

}
}

else if(cityFirstInside {
System.out.println("C1="+cityFirstInside+" C2="+citySecondInside+" max="+max);
if(j==0)
{
max++;
al.add(citySecondInside);
}
else
{


for(int p=0;p {
if(!(citySecondInside>(Integer)al.get(p)))
{
System.out.println("hhh");
flag=true;
break;
}

}
System.out.println(flag);
if(!flag)
{

max++;
al.add(citySecondInside);
// System.out.println("C1="+cityFirstInside+" C2="+citySecondInside+" max="+max);
}
flag=false;
}
}
}

al.clear();

if(max>previousMax)
previousMax = max;
max=0;
}
}
return previousMax;
}



Download the above Code: Click Here

Tuesday, April 2, 2013

Java: Towers Of Hanoi

/*
Towers Of Hanoi.
There are three pegs: A, B and C. There are n disks. All disks are different in size.
The disks are initially stacked on peg A so that they increase in size from the top to the bottom.
The goal is to transfer the entire tower from the A peg to the C peg.
One disk at a time can be moved from the top of a stack either to an empty peg or to
a peg with a larger disk than itself on the top of its stack.

The method should return a sequence of disk moves, each move is a String with two letters (A, B or C)
corresponding to the peg the disk moves from and the peg it moves to.
For example, the move "AC" means that a top disk from peg A should be moved to peg C.
*/

  1. import java.util.ArrayList;

  2. importjava.util.List;

  3.  

  4.  

  5. publicclassTowersOfHanoi {

  6.  

  7.     privatestaticList<String> list= newArrayList<String>();

  8.     staticString a="A";

  9.     staticString c="C";

  10.     staticString b="B";

  11.     staticString s="";

  12.     publicstaticvoidmove(intn, intstartPole, intendPole) {

  13.         if(n== 0){

  14.           return;

  15.         }

  16.         intintermediatePole = 6- startPole - endPole;

  17.         move(n-1, startPole, intermediatePole);

  18.         System.out.println("Move "+n + " from "+ startPole + " to "+endPole);

  19.         if(startPole==1)

  20.             s=s+a;

  21.         if(startPole==2)

  22.             s=s+b;

  23.         if(startPole==3)

  24.             s=s+c;

  25.         if(endPole==1)

  26.             s=s+a;

  27.          

  28.         if(endPole==2)

  29.             s=s+b;

  30.         if(endPole==3)

  31.             s=s+c;

  32.          

  33.         list.add(s);

  34.         s="";

  35.         move(n-1, intermediatePole, endPole);

  36.       }

  37.        

  38.     publicstaticList<String> transferFromAtoC(intn) {

  39.         /*

  40.           Towers Of Hanoi.

  41.           There are three pegs: A, B and C. There are n disks. All disks are different in size.

  42.           The disks are initially stacked on peg A so that they increase in size from the top to the bottom.

  43.           The goal is to transfer the entire tower from the A peg to the C peg.

  44.           One disk at a time can be moved from the top of a stack either to an empty peg or to

  45.           a peg with a larger disk than itself on the top of its stack.

  46.  

  47.           The method should return a sequence of disk moves, each move is a String with two letters (A, B or C)

  48.           corresponding to the peg the disk moves from and the peg it moves to.

  49.           For example, the move "AC" means that a top disk from peg A should be moved to peg C.

  50.          */

  51.          

  52.         move(n, 1, 3);

  53.         returnlist;

  54.     }

  55.       publicstaticvoidmain(String[] args) {

  56.           List l1 = newArrayList();

  57.         transferFromAtoC(1);

  58.         System.out.println(list);

  59.       }

  60. }


Download Link: Click Here

Java: Set Intersection

/*
Please implement this method to
return a Set equal to the intersection of the parameter Sets
The method should not chage the content of the parameters.
*/

  1. import java.util.HashSet;

  2. import java.util.Iterator;

  3. import java.util.NoSuchElementException;

  4. import java.util.Set;


  5. public class SetIntersection {

  6. /**

  7. * @param args

  8. */


  9. private static Set<Object> s1;

  10. private static Set<Object> s2;

  11. public static Set<Object> getIntersection(Set<Object> a, Set<Object> b) {

  12. /*

  13. Please implement this method to

  14. return a Set equal to the intersection of the parameter Sets

  15. The method should not chage the content of the parameters.

  16. */


  17. s1 =a;

  18. s2 = b;

  19. Object ob;

  20. Set<Object> s3 = new HashSet<Object>();



  21. Iterator<Object> it1 = s1.iterator();

  22. Iterator<Object> it2 = s2.iterator();


  23. System.out.println("Set 1");

  24. while(it1.hasNext())

  25. {

  26. System.out.println(it1.next());

  27. }

  28. System.out.println("Set 2");

  29. while(it2.hasNext())

  30. {

  31. System.out.println(it2.next());

  32. }


  33. it1 = s1.iterator();

  34. while(it1.hasNext())

  35. {

  36. System.out.println("hi");

  37. try

  38. {

  39. ob = it1.next();

  40. //System.out.println(ob);

  41. if(s2.contains(ob))

  42. {

  43. // System.out.println("contain element is "+ob);

  44. s3.add(ob);

  45. }

  46. }

  47. catch(ClassCastException cse)

  48. {

  49. cse.printStackTrace();

  50. }

  51. catch(NoSuchElementException ne)

  52. {

  53. ne.printStackTrace();

  54. }



  55. }


  56. return s3;

  57. }



  58. public static void main(String[] args) {

  59. // TODO Auto-generated method stub

  60. Set<Object> s1 = new HashSet<Object>();

  61. Set<Object> s2 = new HashSet<Object>();

  62. s1.add(3);

  63. s1.add(4);

  64. s1.add(5);

  65. s1.add(7);

  66. s1.add("hi");

  67. s1.add(3.4);

  68. s2.add(1);

  69. s2.add(2);

  70. s2.add(3);

  71. s2.add(7);

  72. s2.add("hi");

  73. s2.add(new Object());

  74. Set<Object> s3 = getIntersection(s1,s2);

  75. Iterator<Object> it = s3.iterator();

  76. System.out.println("Set 3");

  77. while(it.hasNext())

  78. {

  79. System.out.println(it.next());

  80. }

  81. }

  82. }


Download Link: Click Here

Java: Prime Number List

/*
Please implement this method to
return a list of all prime numbers in the given range (inclusively).
A prime number is a natural number that has exactly two distinct natural number divisors, which are 1 and the prime number itself.
The first prime numbers are: 2, 3, 5, 7, 11, 13
*/

 

  1. import java.util.List;

  2. import java.util.ArrayList;


  3. public class PrimeNumber {

  4. /**

  5. * @param args

  6. */

  7. public static void main(String[] args) {

  8. // TODO Auto-generated method stub

  9. System.out.println(getPrimeNumbers(481,500));

  10. }

  11. public static List<Integer> getPrimeNumbers(int from, int to) {

  12. /*

  13. Please implement this method to

  14. return a list of all prime numbers in the given range (inclusively).

  15. A prime number is a natural number that has exactly two distinct natural number divisors, which are 1 and the prime number itself.

  16. The first prime numbers are: 2, 3, 5, 7, 11, 13

  17. */


  18. List<Integer> list = new ArrayList<Integer>();

  19. boolean b=false;

  20. for(int j=from;j<=to;j++)

  21. {

  22. b=false;

  23. System.out.println("from "+from);

  24. int i=2;

  25. for(;i<j/2;i++)

  26. {


  27. if(j%i==0)

  28. {

  29. b=true;

  30. break;

  31. }



  32. }

  33. System.out.println("j= "+j);

  34. System.out.println("b= "+b);

  35. if(b==false && j!=1 && j!=0)

  36. list.add(j);


  37. }


  38. System.out.println(list);

  39. return list;

  40. }

  41. }


 

Download Link: Click Here

Java: Positive Number Array

/*
Please implement this method to
return a new array with only positive numbers from the given array.
The elements in the resulting array shall be sorted in the ascending order.

*/

 

  1. public class PositiveNumberArray {

  2. /**

  3. * @param args

  4. */

  5. public static void main(String[] args) {

  6. // TODO Auto-generated method stub

  7. int a[] = {3,5,6,30,-3,-3,-3,5,3,-3};

  8. for(int i : retainPositiveNumbers(a))

  9. System.out.println(i);

  10. }


  11. public static int[] retainPositiveNumbers(int[] a) {

  12. /*

  13. Please implement this method to

  14. return a new array with only positive numbers from the given array.

  15. The elements in the resulting array shall be sorted in the ascending order.


  16. */


  17. int len=0;

  18. int b[];

  19. for(int i=0;i<a.length;i++)

  20. {

  21. if(a[i]>0)

  22. len++;

  23. }



  24. b = new int[len];

  25. for(int i=0,j=0;i<a.length;i++)

  26. {

  27. if(a[i]>0)

  28. {

  29. b[j]=a[i];

  30. j++;

  31. }

  32. }


  33. int temp;

  34. for(int i=0;i<b.length-1;i++)

  35. {

  36. for(int j=i+1;j<b.length;j++)

  37. {

  38. if(b[j]<b[i])

  39. {

  40. temp=b[j];

  41. b[j]=b[i];

  42. b[i]=temp;

  43. }

  44. }


  45. }


  46. return b;

  47. }

  48. }


Download Link: Click Here

Java: String Pailndrome

/*
Definition: A palindrome is a string that reads the same forward and backward.
For example, "abcba" is a palindrome, "abab" is not.
Please implement this method to
return true if the parameter is a palindrome and false otherwise.
*/

 

  1. public class Palindrome {

  2. /**

  3. * @param args

  4. */

  5. public static void main(String[] args) {

  6. // TODO Auto-generated method stub

  7. System.out.println(isPalindrome("cbc"));

  8. }

  9. public static boolean isPalindrome(String s) {

  10. /*

  11. Definition: A palindrome is a string that reads the same forward and backward.

  12. For example, "abcba" is a palindrome, "abab" is not.

  13. Please implement this method to

  14. return true if the parameter is a palindrome and false otherwise.

  15. */


  16. String temp;

  17. int len = s.length();

  18. char []arr = new char[len];

  19. for(int i=len-1,j=0;i>=0;i--,j++)

  20. {


  21. arr[j]=s.charAt(i);

  22. }


  23. temp = new String(arr);

  24. System.out.println("temp "+temp+"\ns "+s);

  25. if(temp.equals(s))

  26. return true;

  27. return false;

  28. }

  29. }


Download Link: Click Here

Java: Get Sum of Numbers in a String

Download Link: http://txtup.net/dQNDr

/*

Source Question: betterprogrammer.com
Please implement this method to
return the sum of all integers found in the parameter String. You can assume that
integers are separated from other parts with one or more spaces (' ' symbol).
For example, s="12 some text 3 7", result: 22 (12+3+7=22)
*/

 

  1. import java.util.regex.Matcher;

  2. import java.util.regex.Pattern;

  3. public class GetSumOfNumbers {

  4. public static void main(String[] args) {


  5. System.out.println(getSumOfNumbers("ss34 gbb 65"));

  6. }


  7. public static int getSumOfNumbers(String s) {

  8. /*

  9. Please implement this method to

  10. return the sum of all integers found in the parameter String. You can assume that

  11. integers are separated from other parts with one or more spaces (' ' symbol).

  12. For example, s="12 some text 3 7", result: 22 (12+3+7=22)

  13. */

  14. //s="kkk 4 jj 9d kj 99 kjdj 9 kj 9";

  15. Pattern p = Pattern.compile("\\d+");

  16. Matcher m = p.matcher(s);

  17. int sum=0;

  18. while(m.find())

  19. {

  20. //System.out.println(m.start()+" "+m.end());

  21. sum = sum + Integer.parseInt(s.substring(m.start(), m.end()));

  22. }


  23. return sum;

  24. }

  25. }


Download Link: http://txtup.net/dQNDr

Wednesday, March 20, 2013

The Great Indian Programming League 2013 - March Edition Level:Medium

Here is the Link of question and description of 

Four Persons


I am providing you the solution of the above question.


Mybest score on this is 99.99.



Repost Code with better one.(Download COde)
cvcv

____________________________________________________________



 

  1. public class InterchangePosition {


  2. /**

  3. * @param args

  4. */

  5. public static void main(String[] args) {

  6. // TODO Auto-generated method stub

  7. String []arr = {"5#1","6#1","5#3"};

  8. long x1 = System.currentTimeMillis();

  9. System.out.println(get_height(arr));

  10. long x2 = System.currentTimeMillis();

  11. System.out.println("TIme in milli "+(x2-x1));

  12. }

  13. public static int get_height(String[] input1)

  14.     {

  15.         //Write code here


  16. int count=0;


  17. int f[] = new int[input1.length];


  18. int value=0;

  19. String s[]= new String[2];


  20. if(input1.length==0)

  21. return 0;


  22. for(int i=0;i

  23. {


  24. if(Integer.parseInt(((s=input1[i].split("#"))[0]))<4 || Integer.parseInt(s[0])>7

  25. || Integer.parseInt(s[1])<0 || Integer.parseInt(s[1])>11

  26. )

  27. {

  28. //System.out.println("boom1");

  29. return -1;

  30. }



  31. f[i] = (Integer.parseInt(s[0])) * 12 +  Integer.parseInt(s[1]);



  32. }



  33. for(int i : f)

  34. {

  35. System.out.println(""+i);

  36. }

  37. System.out.println("--------------");



  38. for(int i=0;i<f.length;i++)

  39. {

  40. for(int j=i+1;j<f.length;j++)

  41. {



  42. if(f[i]>f[j])

  43. {

  44. //System.out.println("I am in "+f[i]);

  45. count++;

  46. }

  47. }

  48. }

  49. return count;

  50.     }


  51. }


____________________________________________________________

Another One
Download Code: Click Here


Mirror: Click Here

___________________________________________________________


public class InterchangePosition {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String []arr = {"5#5","6#6","5#5","6#6","5#11"};
long x1 = System.currentTimeMillis();
System.out.println(get_height(arr));
long x2 = System.currentTimeMillis();
System.out.println("TIme in milli "+(x2-x1));
}
public static int get_height(String[] input1)
{
//Write code here

int count=0;

int f[] = new int[input1.length];

int value=0;


if(input1.length==0)
return 0;

try
{
for(int i=0;i{

if(Integer.parseInt(input1[i].substring(0, input1[i].indexOf('#')))<4 ||
Integer.parseInt(input1[i].substring(0, input1[i].indexOf('#')))>7)
{
//System.out.println("boom1");
return -1;
}
if(Integer.parseInt(input1[i].substring(input1[i].indexOf('#')+1))<0 ||
Integer.parseInt(input1[i].substring(input1[i].indexOf('#')+1))>11)
{
//System.out.println("boom2");
return -1;
}

value = (Integer.parseInt(input1[i].substring(0, input1[i].indexOf('#')))) * 12 +  Integer.parseInt(input1[i].substring(input1[i].indexOf('#')+1));
f[i] = value;

}
}
catch(NumberFormatException nf)
{
nf.printStackTrace();
return -1;
}


for(int i : f)
{
System.out.println(""+i);
}
System.out.println("--------------");


for(int i=0;i<f.length;i++){
for(int j=i+1;j<f.length;j++){


if(f[i]>f[j])
{
//System.out.println("I am in "+f[i]);
count++;
}
}
}
return count;
}

}





___________________________________________________________

Download Code: Click Here

Mirror: Click Here






The Great Indian Programming League 2013 - March Edition Level:Medium

Here is the Link of question and description of 

Four Persons

I am providing you the solution of the above question. My best score on this is 99.99.

Repost Code with better one.(Download COde)


____________________________________________________________




  1. public class InterchangePosition {

  2. /**
  3. * @param args
  4. */
  5. public static void main(String[] args) {
  6. // TODO Auto-generated method stub
  7. String []arr = {"5#1","6#1","5#3"};
  8. long x1 = System.currentTimeMillis();
  9. System.out.println(get_height(arr));
  10. long x2 = System.currentTimeMillis();
  11. System.out.println("TIme in milli "+(x2-x1));
  12. }
  13. public static int get_height(String[] input1)
  14.     {
  15.         //Write code here
  16. int count=0;
  17. int f[] = new int[input1.length];
  18. int value=0;
  19. String s[]= new String[2];
  20. if(input1.length==0)
  21. return 0;
  22. for(int i=0;i
  23. {
  24. if(Integer.parseInt(((s=input1[i].split("#"))[0]))<4 || Integer.parseInt(s[0])>7
  25. || Integer.parseInt(s[1])<0 || Integer.parseInt(s[1])>11
  26. )
  27. {
  28. //System.out.println("boom1");
  29. return -1;
  30. }
  31. f[i] = (Integer.parseInt(s[0])) * 12 +  Integer.parseInt(s[1]);
  32. }
  33. for(int i : f)
  34. {
  35. System.out.println(""+i);
  36. }
  37. System.out.println("--------------");
  38. for(int i=0;i<f.length;i++)
  39. {
  40. for(int j=i+1;j<f.length;j++)
  41. {
  42. if(f[i]>f[j])
  43. {
  44. //System.out.println("I am in "+f[i]);
  45. count++;
  46. }
  47. }
  48. }
  49. return count;
  50.     }

  51. }


____________________________________________________________

Another One
Download Code: Click Here 
Mirror: Click Here
___________________________________________________________


public class InterchangePosition {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String []arr = {"5#5","6#6","5#5","6#6","5#11"};
long x1 = System.currentTimeMillis();
System.out.println(get_height(arr));
long x2 = System.currentTimeMillis();
System.out.println("TIme in milli "+(x2-x1));
}
public static int get_height(String[] input1)
    {
        //Write code here

int count=0;

int f[] = new int[input1.length];

int value=0;


if(input1.length==0)
return 0;

try
{
for(int i=0;i {

if(Integer.parseInt(input1[i].substring(0, input1[i].indexOf('#')))<4 ||
  Integer.parseInt(input1[i].substring(0, input1[i].indexOf('#')))>7)
{
//System.out.println("boom1");
return -1;
}
if(Integer.parseInt(input1[i].substring(input1[i].indexOf('#')+1))<0 ||
  Integer.parseInt(input1[i].substring(input1[i].indexOf('#')+1))>11)
{
//System.out.println("boom2");
return -1;
}

value = (Integer.parseInt(input1[i].substring(0, input1[i].indexOf('#')))) * 12 +  Integer.parseInt(input1[i].substring(input1[i].indexOf('#')+1));
f[i] = value;

}
}
catch(NumberFormatException nf)
{
nf.printStackTrace();
return -1;
}


for(int i : f)
{
System.out.println(""+i);
}
System.out.println("--------------");


for(int i=0;i
<f.length;i++) {
for(int j=i+1;j<f.length;j++) {


if(f[i]>f[j])
{
//System.out.println("I am in "+f[i]);
count++;
}
}
}
return count;
    }

}



___________________________________________________________
Download Code: Click Here 
Mirror: Click Here



Monday, March 11, 2013

TechGig: The Great Indian Programming League 2013 - Jan Edition


Fashion Contest 2013


My Score: 99.99 
Test Cases Passed: 8

import java.io.*;
  1. public class CandidateCode
  2. {
  3. public static int fashion(int[] input1)
  4. {
  5. //Write code here
  6. int totalJudges = input1.length;
  7. if(totalJudges==0)
  8. return 0;
  9. else if(totalJudges==1)
  10. return input1[0];
  11. else
  12. {
  13. int centerJudge = (totalJudges+1)/2-1;
  14. int centerJudgeScore = input1[centerJudge];
  15. for(int i=0,j=1;i
  16. {
  17. if(input1[centerJudge-j]==input1[centerJudge+j])
  18. centerJudgeScore+=input1[centerJudge+j];
  19. }
  20. return centerJudgeScore;
  21. }
  22. }
  23. }

TechGig: The Great Indian Programming League 2013 - Jan Edition


Fashion Contest 2013


My Score: 99.99 
Test Cases Passed: 8

import java.io.*;
  1. public class CandidateCode
  2. {
  3. public static int fashion(int[] input1)
  4. {
  5. //Write code here
  6. int totalJudges = input1.length;
  7. if(totalJudges==0)
  8. return 0;
  9. else if(totalJudges==1)
  10. return input1[0];
  11. else
  12. {
  13. int centerJudge = (totalJudges+1)/2-1;
  14. int centerJudgeScore = input1[centerJudge];
  15. for(int i=0,j=1;i
  16. {
  17. if(input1[centerJudge-j]==input1[centerJudge+j])
  18. centerJudgeScore+=input1[centerJudge+j];
  19. }
  20. return centerJudgeScore;
  21. }
  22. }
  23. }

Java Utility Functions - Password Generation and Validation

Function 1: Generate a random password that's 7 characters. The random password MUST have 1 lowercase, 1 uppercase, 1 digit, and 1 symbol (valid symbols are ! @ # $ % *

Method signature should be
public static String generatePassword()

Function 2: Validate a passed in password. This password will be between 7 and 20 characters. It must comply with at least 3 of the following 4 rules: 1) at least 1 capital 2) at least one lowercase 3) at least 1 digit 4) at least 1 symbol (see above for valid symbols). If the password is too long or too short, return false. If it only meets 2 of the rules, return false. If it meets 3 or 4 of the rules, return true.

Method signature should be
public static boolean validatePassword(String password)



  1. package password;

  2. import java.util.Arrays;
  3. import java.util.Collection;
  4. import java.util.Collections;
  5. import java.util.Random;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;

  8. public class RandomPassword
  9. {
  10. private static String password;
  11. // Method for gnerating random password each time
  12. public static String generatePassword()
  13. {
  14. password="";
  15. String temp[] = new String[7];
  16. char []number = new char[]{'0','1','2','3','4','5','6','7','8','9'};
  17. char []lowerCase = new char[]{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
  18. char []upperCase = new char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
  19. char []symbol = new char[]{'!','@','#','$','%','*'};
  20. char []allCase = new char[]{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',
  21. 'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U',
  22. 'V','W','X','Y','Z','!','@','#','$','%','*'};
  23. Random random = new Random();
  24. int position = random.nextInt(10);
  25. temp[0] = ""+number[position];
  26. position = random.nextInt(26);
  27. temp[1] = ""+lowerCase[position];
  28. position = random.nextInt(26);
  29. temp[2] = ""+upperCase[position];
  30. position = random.nextInt(6);
  31. temp[3] = ""+symbol[position];
  32. for(int i=0;i3>
  33. {
  34. position = random.nextInt(68);
  35. temp[4+i] = "" +allCase[position];
  36. }
  37. // Suffle Your password
  38. Collections.shuffle(Arrays.asList(temp));
  39. // temp[] to String
  40. for(String pass : temp)
  41. password=password+pass;
  42. return password;
  43. }
  44. //Method for validate password
  45. public static boolean validatePassword(String password)
  46. {
  47. int flag=0;
  48. // Validate Length 
  49. if(password.length()20)7>
  50. return false;
  51. Pattern p = Pattern.compile("[a-z]");
  52. Matcher m = p.matcher(password);
  53. while(m.find())
  54. {
  55. flag++;
  56. break;
  57. }

  58. p = Pattern.compile("[A-Z]");
  59. m = p.matcher(password);
  60. while(m.find())
  61. {
  62. flag++;
  63. break;
  64. }
  65.  
  66. p = Pattern.compile("\\d");
  67. m = p.matcher(password);
  68. while(m.find())
  69. {
  70. flag++;
  71. break;
  72. }
  73.  
  74. p = Pattern.compile("['!','@','#','$','$',''%','*']");
  75. m = p.matcher(password);
  76. while(m.find())
  77. {
  78. flag++;
  79. break;
  80. }
  81.  
  82.  
  83. if(flag==0 || flag==1 || flag==2)
  84. return false;
  85.  
  86. if(flag==3 || flag==4)
  87. return true;
  88.  
  89. return true;
  90. }
  91. public static void main(String[] args) {
  92. System.out.println("passwors id "+RandomPassword.generatePassword());
  93. System.out.println(RandomPassword.validatePassword("aaaAaa)aa"));
  94. }
  95. }
Or

Java Utility Functions - Password Generation and Validation

Function 1: Generate a random password that's 7 characters. The random password MUST have 1 lowercase, 1 uppercase, 1 digit, and 1 symbol (valid symbols are ! @ # $ % *

Method signature should be
public static String generatePassword()

Function 2: Validate a passed in password. This password will be between 7 and 20 characters. It must comply with at least 3 of the following 4 rules: 1) at least 1 capital 2) at least one lowercase 3) at least 1 digit 4) at least 1 symbol (see above for valid symbols). If the password is too long or too short, return false. If it only meets 2 of the rules, return false. If it meets 3 or 4 of the rules, return true.

Method signature should be
public static boolean validatePassword(String password)



  1. package password;

  2. import java.util.Arrays;
  3. import java.util.Collection;
  4. import java.util.Collections;
  5. import java.util.Random;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;

  8. public class RandomPassword
  9. {
  10. private static String password;
  11. // Method for gnerating random password each time
  12. public static String generatePassword()
  13. {
  14. password="";
  15. String temp[] = new String[7];
  16. char []number = new char[]{'0','1','2','3','4','5','6','7','8','9'};
  17. char []lowerCase = new char[]{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
  18. char []upperCase = new char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
  19. char []symbol = new char[]{'!','@','#','$','%','*'};
  20. char []allCase = new char[]{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',
  21. 'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U',
  22. 'V','W','X','Y','Z','!','@','#','$','%','*'};
  23. Random random = new Random();
  24. int position = random.nextInt(10);
  25. temp[0] = ""+number[position];
  26. position = random.nextInt(26);
  27. temp[1] = ""+lowerCase[position];
  28. position = random.nextInt(26);
  29. temp[2] = ""+upperCase[position];
  30. position = random.nextInt(6);
  31. temp[3] = ""+symbol[position];
  32. for(int i=0;i<3 i="" span="">
  33. {
  34. position = random.nextInt(68);
  35. temp[4+i] = "" +allCase[position];
  36. }
  37. // Suffle Your password
  38. Collections.shuffle(Arrays.asList(temp));
  39. // temp[] to String
  40. for(String pass : temp)
  41. password=password+pass;
  42. return password;
  43. }
  44. //Method for validate password
  45. public static boolean validatePassword(String password)
  46. {
  47. int flag=0;
  48. // Validate Length 
  49. if(password.length()<7 password.length="">20)
  50. return false;
  51. Pattern p = Pattern.compile("[a-z]");
  52. Matcher m = p.matcher(password);
  53. while(m.find())
  54. {
  55. flag++;
  56. break;
  57. }

  58. p = Pattern.compile("[A-Z]");
  59. m = p.matcher(password);
  60. while(m.find())
  61. {
  62. flag++;
  63. break;
  64. }
  65.  
  66. p = Pattern.compile("\\d");
  67. m = p.matcher(password);
  68. while(m.find())
  69. {
  70. flag++;
  71. break;
  72. }
  73.  
  74. p = Pattern.compile("['!','@','#','$','$',''%','*']");
  75. m = p.matcher(password);
  76. while(m.find())
  77. {
  78. flag++;
  79. break;
  80. }
  81.  
  82.  
  83. if(flag==0 || flag==1 || flag==2)
  84. return false;
  85.  
  86. if(flag==3 || flag==4)
  87. return true;
  88.  
  89. return true;
  90. }
  91. public static void main(String[] args) {
  92. System.out.println("passwors id "+RandomPassword.generatePassword());
  93. System.out.println(RandomPassword.validatePassword("aaaAaa)aa"));
  94. }
  95. }
Or