Tuesday, 30 June 2015

Rotation point in sorted Array

Array A is sorted in ascending order, and rotated at some random point. Write a program to figure out this random point.

As per problem statement, array A is sorted in ascending order, and rotated (Assume elements are rotated clock wise) at some random point, so input looks like

For the input,
A = [56, 78, 85, 91, 109, 123, 145, 159, 165, 200, 245]

If Array A is rotated clockwise 4 times, then it becomes like following.

A = [159, 165, 200, 245, 56, 78, 85, 91, 109, 123, 145]

In the above case, rotation point is 56, it is at index 4.

In given problem, elements in array are sorted, so we can utilize this.

Logic is simple, find middle element and compare it with elements in low and high positions, decide on which way (left/right) you should travel.

If A[mid] <= A[high])  we have to traverse left.

If(A[mid] > A[low]) we have to traverse right.

public class FindRotationPoint {

 public static int getRotationPoint(int arr[]) {

  /* Check null condition */
  if (arr == null) {
   throw new NullPointerException();
  }

  if (arr.length <= 2) {
   return 0;
  }

  int low = 0, high = arr.length - 1;
  int mid = (low + high) / 2;

  while (low < high) {
   if (arr[mid] <= arr[high]) {
    high = mid;
   } else if (arr[mid] > arr[low]) {
    low = mid;
   }
   mid = (low + high) / 2;
  }
  return high;
 }
}


import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class FindRotationPointTest {

 @Test(expected = NullPointerException.class)
 public void testNullCondition() {
  FindRotationPoint.getRotationPoint(null);
 }

 @Test
 public void testSingleElement() {
  int arr[] = { 5 };
  assertEquals(0, FindRotationPoint.getRotationPoint(arr));
 }

 @Test
 public void testDoubleElement() {
  int arr[] = { 5, 6 };
  assertEquals(0, FindRotationPoint.getRotationPoint(arr));
 }

 @Test
 public void testNormal_1() {
  int arr[] = { 159, 165, 200, 245, 56, 78, 85, 91, 109, 123, 145 };
  assertEquals(4, FindRotationPoint.getRotationPoint(arr));
 }

 @Test
 public void testNormal_2() {
  int arr[] = { 159, 165, 200, 245, 342, 456, 56, 78, 85, 91, 109, 123,
    145 };
  assertEquals(6, FindRotationPoint.getRotationPoint(arr));
 }

 @Test
 public void testNormal_3() {
  int arr[] = { 1, 2, 3, 4, 5 };
  assertEquals(0, FindRotationPoint.getRotationPoint(arr));
 }

 @Test
 public void testduplicates_1() {
  int arr[] = { 159, 165, 200, 245, 342, 7, 7, 7, 98, 100, 120 };
  assertEquals(5, FindRotationPoint.getRotationPoint(arr));
 }

 @Test
 public void testduplicates_2() {
  int arr[] = { 5, 5, 5, 5, 5, 5 };
  assertEquals(0, FindRotationPoint.getRotationPoint(arr));
 }

 @Test
 public void testduplicates_3() {
  int arr[] = { 12, 13, 14, 5, 5, 5, 6, 7, 8 };
  assertEquals(3, FindRotationPoint.getRotationPoint(arr));
 }

}


Learn Programming


Find element in a sorted matrix
Shift zeros to left and non-zeros to right
Reverse elements of array
Check whether a string is funny or not
Check for pangram
Reverse first n elements of array
Reverse string using recursion
Reverse array using recursion
Generic program to reverse elements of array
Rotate elements in an array (anti clock wise)
Frequency of numbers in array
Sort an array of three color balls
Longest positive sequence in array
Sort array of 0’s and 1’s
Print array in spiral shape
Solve following function
Retrieve unique instances of duplicate elements
Find start position of second sub array
Arrange elements of an array in random order
Move elements in even position to left and odd positions to right
Move elements in even position to left and odd positions to right (Maintain order)
Remove same adjacent character in a string
Find total deleted characters in string
Find lonely number in array
Find intersection of two arrays
Shift all zeros to left and non-zeros to right
Find pairs of numbers where sum equal to x
Sorted array to element:frequency format
Check whether two integers are equal without using comparison operator
Largest sum contiguous subarry
Find all paths
Find all paths from source to destination
Find duplicates from a given list of numbers
Bracket matching problem
Find common elements in two sorted arrays
Replace spaces in a character array with %20
Remove couples from a string
Find triplets where sum is equal to x
Find first non-repeating character in a string
Print distinct elements in every window of size k
Sort an array according to other array
Find smallest and second smallest element in array
Find minimum element in rotated array (Assume array is rotated clock wise)
How to know whether a number is power of 2
Count all set bits in an integer
Count all unset bits in an integer
Check whether nth bit is set or not
Check number is even or odd without division
Set nth bit of a number
Toggle nth bit
Low-level bit hacks that every programmer must know
Check for proper string
Minimum Number of Platforms Required for a Railway Station
Merge two sorted arrays
Find Next greater element
Partition Array
Linked List Java program
Transform one string to another
Program to build max heap
Program to build min heap
Merge Sort
Quick sort
Heap sort
print stars using recursion
Print up down stars
Print number of dots
Draw triangle using recursion
multiply two numbers recursively
compute exponent recursively
Print numbers from n to 0 recursively
Print numbers from 0 to n recursively
Reverse a string using recursion
Check for a prime number using recursion
Recursion to sum numbers from 1 to n
Recursive function to find minimum element in array
Recursion to find sum of elements in array
Recursive implementation of Binary search
Sum of digits using recursion
Recursive program to find maximum in array
Recursively find whether array is ordered or not
Find mean of array recursively
First element added with the second, the second with the third
Insertion Sort Java
Selection Sort Java
Infix to postfix converter program java
Find minimum element in array
Remove duplicate elements from array
Sum Of two arrays
Reverse an array in subset of N
Print the count of characters in duplicate array
Write a function to figure out if someone has won in a game of tic-tac-toe.
Find the missing element
Find the max product value of 3 numbers
Find the first element that appears an even number of times
Find the element that appears once in an array
Convert integers into roman equivalents
Count number of occurrences of a string
Find the permutations of a string
Add element to the end of stack
Reverse the elements of stack
Suppose there are 'N' stairs, a person wants to reach the top. Person can climb either 1 (or) 2 stairs at a time.Count the number of ways that a person can reach the top.
Java program to find cycle in a directed graph
Java program to find a cycle in undirected graph
Check whether number is even or odd using bitwise operator
Merge sort iterative implementation
Check whether array contain a duplicate value or not
Find the smallest digit and its positions in a given number
Implementing a Stack Data Structure in Java Using ArrayList

R : dput : Write an object to a file

“dput” function writes ASCII representation of an object to a file (or) connection.

Syntax
dput(x, file = "",
     control = c("keepNA", "keepInteger", "showAttributes"))


Parameter
Description
x
Object to be written to a file.
file
Represents a file (or) a connection.
control
Character vector specifies de-parsing options

> table1 = data.frame(id=1:4, firstName=c("Hari Krishna","Joel","Rama Krishna","Sudheer"))
> dput(table1, "out.R")
> 
> list.files()
[1] "dump.txt"     "employee.csv" "employee.txt" "myFunction.R" "out.R"        "output.txt"  

“out.R” contains following data

structure(list(id = 1:4, firstName = structure(1:4, .Label = c("Hari Krishna",
"Joel", "Rama Krishna", "Sudheer"), class = "factor")), .Names = c("id",

"firstName"), row.names = c(NA, -4L), class = "data.frame")



Prevoius                                                 Next                                                 Home