Showing posts with label Java Challenge. Show all posts
Showing posts with label Java Challenge. Show all posts

Thursday, June 9, 2016

StrSymmetryPoint in Java & C# - Codility 100%

Link task : https://codility.com/programmers/task/str_symmetry_point/
The idea is checking if string S is having an odd element or event. If it's an even then we should return -1. Then we start comparing every char from the middle to the start index and to the end of the string char index. if we find a different char the return -1. If not the we return index of middle char of the string.

Java Solution :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public static int strSymPoint(String S)
 {
  if(S.length() == 0 || S.length()%2 == 0) return -1;
  int toStart = (S.length()/2)-1;
  int toEnd = (S.length()/2)+1;
  
  while(toStart >= 0)
  {
   if(S.charAt(toStart) != S.charAt(toEnd)) return -1;
   toStart -= 1;
   toEnd += 1;
  }
  return S.length()/2;
 }

Result :

C# solution :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 public static int strSymPoint(string S)
        {
            if (S.Length == 0 || S.Length % 2 == 0) return -1;
            int toStart = (S.Length / 2) - 1;
            int toEnd = (S.Length / 2) + 1;

            while (toStart >= 0)
            {
                if (S[toStart]!= S[toEnd]) return -1;
                toStart -= 1;
                toEnd += 1;
            }
            return S.Length / 2;
        }

Result :

TreeHeight in Java & C# - Codility

Task : https://codility.com/programmers/task/tree_height/

Solution for Java :
1
2
3
4
5
6
7
8
class Solution {
    public int solution(Tree T) {
        // write your code in Java SE 8
        if(T == null) return -1;
  
  return 1+Math.max(solution(T.l), solution(T.r));
    }
}

Result :
Solution for C# :
1
2
3
4
5
6
public int solution(Tree T) {
        // write your code in C# 6.0 with .NET 4.5 (Mono)
        if(T == null) return -1;
  
  return 1+Math.Max(solution(T.l), solution(T.r));
    }

Result :

Tuesday, June 7, 2016

MaxCounters 100% Ala Hisoka - Codility

Berikut kode dalam bahasa Java & C# untuk memperoleh nilai 100% di training test codility MaxCounters

Bahasa Java :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  public static int[] solution100(int N, int[] A) {
         // write your code in Java SE 8
         int[] result = new int[N];
         int max = 0, save_max = 0;
         
         for(int el = 0; el<A.length; el++)
   {
    if(A[el] == N+1)
    {
     save_max = max;
    }else
    {
     if(result[A[el]-1] < save_max) result[A[el]-1] = save_max+1;
     else result[A[el]-1] += 1;
     max = result[A[el]-1]>max? result[A[el]-1]:max;
    } 
   
   }
         
         for(int l=0; l<result.length; l++)
         {
          if(result[l]<save_max) result[l] = save_max;
         }
         
   return result;
         
     }

Bahasa C# :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public static int[] maxCount(int N, int[] A)
        {
            int[] result = new int[N];
            int max = 0, save_max = 0;

            for (int el = 0; el < A.Length; el++)
            {
                if (A[el] == N + 1)
                {
                    save_max = max;
                }
                else
                {
                    if (result[A[el] - 1] < save_max) result[A[el] - 1] = save_max + 1;
                    else result[A[el] - 1] += 1;
                    max = result[A[el] - 1] > max ? result[A[el] - 1] : max;
                }

            }

            for (int l = 0; l < result.Length; l++)
            {
                if (result[l] < save_max) result[l] = save_max;
            }

            return result;
        }
    }


Hasil Test untuk Java :
Hasil Test untuk C# :


Manual Right Cyclic Array Rotation Ala Hyosoka di Java

Method yang ini bisa dipake buat right cyclic array rotation,... Daan methodnya udah lulus uji dari codility... Berikut Kodenya :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
/*
  * A = array yang akan dirotasi
  * k = besar rotasi ke kanan
  */
 
 public static int[] cyclicRotation(int[] A, int k)
 {
  if(A.length<=1) return A;
  int[] temp = new int[A.length];
  int rot = (k/A.length) > 0 ? k%A.length: k;
  for(int i=0; i<A.length; i++)
  {
   if(A.length - i > rot) temp[rot+i] = A[i];
   else temp[rot-(A.length-i)] = A[i];
  }
  return temp;
 }

Hasil Uji dari Codiliti :


Sorting & Binarysearch Array di Java

mmmm...... to the point :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package hisoka.poipo;

import java.util.Arrays;

public class MainArraySorting {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int[] hisoka = {-1,8, 4,7,2,10,3,2};
  displayArray(hisoka);
  Arrays.sort(hisoka);
  System.out.println("\nSetelah di sort : ");
  displayArray(hisoka);
  
  //ini pake binarySearch
  int indeks = Arrays.binarySearch(hisoka, 7);
  System.out.println(indeks);
 }
 
 
 public static void displayArray(int[] A)
 {
  for (int a: A)
  {
   System.out.print(a+" ");
  }
  System.out.print("\n");
 }

}

Hasil :
Sooo..untuk ngesort array itu pake cara di line 11, terus klu binarySearch di line 16 ehehe.. :D

Monday, June 6, 2016

Java Challenge - count8 Recursive

Given a non-negative int n, compute recursively (no loops) the count of the occurrences of 8 as a digit, except that an 8 with another 8 immediately to its left counts double, so 8818 yields 4. Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).

count8(8) → 1
count8(818) → 2
count8(8818) → 4

Hisoka:
1
2
3
4
5
6
public int count8(int n) {
 if(n<10 && n == 8) return 1; 
 if(n<10 && n!=8) return 0;
 if((n%10 == 8) && ((n/10)%10)==8) return 1+count8(n%10)+count8(n/10);
 return count8(n%10)+count8(n/10);
}

Test result from decodingbat:

Java Challenge - count7 Recursive

Given a non-negative int n, return the count of the occurrences of 7 as a digit, so for example 717 yields 2. (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).

count7(717) → 2
count7(7) → 1
count7(123) → 0

Hisoka :
1
2
3
4
5
public int count7(int n) {
  if(n<10 && n == 7) return 1;
  else if(n<10 && n!=7) return 0;
  else return count7(n%10)+count7(n/10);
}

Test Result of Codingbat:

Java Challenge - sumDigits Recursive

Given a non-negative int n, return the sum of its digits recursively (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).

sumDigits(126) → 9
sumDigits(49) → 13
sumDigits(12) → 3

Hisoka's Trick :
1
2
3
4
public int sumDigits(int n) {
   if(n < 10) return n;
   return n%10 + sumDigits(n/10);
}

Test Result:

Java Challenge - Triangle Recursive

We have triangle made of blocks. The topmost row has 1 block, the next row down has 2 blocks, the next row has 3 blocks, and so on. Compute recursively (no loops or multiplication) the total number of blocks in such a triangle with the given number of rows.

triangle(0) → 0
triangle(1) → 1
triangle(2) → 3

Hisoka :
1
2
3
4
public int triangle(int rows) {
  if (rows == 0) return 0;
  return rows+triangle(rows-1);
}

Test Result:

Java Challenge - bunnyEars2 Recursive

We have bunnies standing in a line, numbered 1, 2, ... The odd bunnies (1, 3, ..) have the normal 2 ears. The even bunnies (2, 4, ..) we'll say have 3 ears, because they each have a raised foot. Recursively return the number of "ears" in the bunny line 1, 2, ... n (without loops or multiplication).

bunnyEars2(0) → 0
bunnyEars2(1) → 2
bunnyEars2(2) → 5

Hisoka :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public int bunnyEars2(int bunnies) {
  if (bunnies == 0) return 0;
  else if( bunnies % 2 == 0)//genap
  {
      return 3+bunnyEars2(bunnies-1);
  }else
   {
      return 2+bunnyEars2(bunnies-1);
   }
}

Hasil Test :

Java Challenge - fibonacci recursive

The fibonacci sequence is a famous bit of mathematics, and it happens to have a recursive definition. The first two values in the sequence are 0 and 1 (essentially 2 base cases). Each subsequent value is the sum of the previous two values, so the whole sequence is: 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on. Define a recursive fibonacci(n) method that returns the nth fibonacci number, with n=0 representing the start of the sequence.

fibonacci(0) → 0
fibonacci(1) → 1
fibonacci(2) → 1

Hisoka :
1
2
3
4
public int fibonacci(int n) {
  if(n == 0 || n == 1) return n;
  return fibonacci(n-1)+fibonacci(n-2);
}

Hasil:

Codingbat:
Codingbat g' ngasih jawaban... :v

Java Challenge - factorial

Given n of 1 or more, return the factorial of n, which is n * (n-1) * (n-2) ... 1. Compute the result recursively (without loops).

factorial(1) → 1
factorial(2) → 2
factorial(3) → 6

Hisoka:
1
2
3
4
public int factorial(int n) {
  if(n == 1) return 1;
  return n*factorial(n-1);
}

Hasil:

Codingbat:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public int factorial(int n) {
  // Base case: if n is 1, we can return the answer directly
  if (n == 1) return 1;
  
  // Recursion: otherwise make a recursive call with n-1
  // (towards the base case), i.e. call factorial(n-1).
  // Assume the recursive call works correctly, and fix up
  // what it returns to make our result.
  return n * factorial(n-1);
}

Woooh...sama yaaak... :D

Sunday, June 5, 2016

Java Challenge - stringX - warm_up_2

Given a string, return a version where all the "x" have been removed. Except an "x" at the very start or end should not be removed.

stringX("xxHxix") → "xHix"
stringX("abxxxcd") → "abcd"
stringX("xabxxxcdx") → "xabcdx"

Hisoka:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public String stringX(String str)
{
  if(str.length() > 1 && str.charAt(0) == 'x' && str.charAt(str.length()-1) == 'x')
   {
    return "x"+str.replace("x","")+"x";
   }else if(str.contains("x") && str.length()!=1)
   {
     return str.replace("x", "");
   }else
   {
    return str;
   }
}

Hasil:

Codingbat:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public String stringX(String str) {
  String result = "";
  for (int i=0; i<str.length(); i++) {
    // Only append the char if it is not the "x" case
    if (!(i > 0 && i < (str.length()-1) && str.substring(i, i+1).equals("x"))) {
      result = result + str.substring(i, i+1); // Could use str.charAt(i) here
    }
  }
  return result;
}

Java Challenge - stringMatch - warm_up_2

Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.

stringMatch("xxcaazz", "xxbaaz") → 3
stringMatch("abc", "abc") → 2
stringMatch("abc", "axc") → 0
Hisoka:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public int stringMatch(String a, String b) {
  int count = 0;
  int length = a.length() > b.length() ? b.length():a.length();
  for(int i=0; i<length-1; i++)
  {
    if(a.substring(i, i+2).equalsIgnoreCase(b.substring(i, i+2)))count++;
   }
  
   return count;
}

Hasil:

Codingbat:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public int stringMatch(String a, String b) {
  // Figure which string is shorter.
  int len = Math.min(a.length(), b.length());
  int count = 0;
  
  // Look at both substrings starting at i
  for (int i=0; i<len-1; i++) {
    String aSub = a.substring(i, i+2);
    String bSub = b.substring(i, i+2);
    if (aSub.equals(bSub)) {  // Use .equals() with strings
      count++;
    }
  }

  return count;
}

Java Challenge - array123 - warm_up_2

Given an array of ints, return true if .. 1, 2, 3, .. appears in the array somewhere.

array123([1, 1, 2, 3, 1]) → true
array123([1, 1, 2, 4, 1]) → false
array123([1, 1, 2, 1, 2, 3]) → true

Hisoka :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public boolean array123(int[] nums) {
  boolean satu=false,dua=false,tiga = false;
  for(int a:nums)
  {
    if(a == 1)satu = true;
    else if(a == 2) dua = true;
    else if(a == 3) tiga = true;   
  }
  return satu && dua && tiga;
}

Hasil :
Codingbat:

1
2
3
4
5
6
7
public boolean array123(int[] nums) {
  // Note: iterate < length-2, so can use i+1 and i+2 in the loop
  for (int i=0; i < (nums.length-2); i++) {
    if (nums[i]==1 && nums[i+1]==2 && nums[i+2]==3) return true;
  }
  return false;
}

Java Challenge - arrayFront9 - warm_up_2

Given an array of ints, return true if one of the first 4 elements in the array is a 9. The array length may be less than 4.

arrayFront9([1, 2, 9, 3, 4]) → true
arrayFront9([1, 2, 3, 4, 9]) → false
arrayFront9([1, 2, 3, 4, 5]) → false
Hisoka :
1
2
3
4
5
6
7
8
public boolean arrayFront9(int[] nums) {
  for(int i=0; i<nums.length; i++)
  {
    if (i > 3)break;
    if (nums[i] == 9) return true;
  }
  return false;
}

Hasilnya :

Codingbat:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public boolean arrayFront9(int[] nums) {
  // First figure the end for the loop
  int end = nums.length;
  if (end > 4) end = 4;
  
  for (int i=0; i<end; i++) {
    if (nums[i] == 9) return true;
  }
  
  return false;
}

Java Challenge - arrayCount9 - warm_up_2

Given an array of ints, return the number of 9's in the array.

arrayCount9([1, 2, 9]) → 1
arrayCount9([1, 9, 9]) → 2
arrayCount9([1, 9, 9, 3, 9]) → 3

Hisoka :
1
2
3
4
5
6
7
8
9
public int arrayCount9(int[] nums) {
  int count = 0;
  for( int a : nums)
    {
       if(a == 9) count++;
    }
  
  return count;
}


Codingbat :
1
2
3
4
5
6
7
8
9
public int arrayCount9(int[] nums) {
  int count = 0;
  for (int i=0; i<nums.length; i++) {
    if (nums[i] == 9) {
      count++;
    }
  }
  return count;
}