Jarvis March Algo not working. condition always false - java

using this link, i saw an algo about the gift wrapping algorithm / jarvis march
https://www.cs.duke.edu/courses/fall14/cps130/notes/scribe14.pdf
i tried coding it but it doesnt follow the algo.
here is my main function
import java.util.Random;
import java.util.Scanner;
public class driver {
static Point[] points;
static Scanner scan = new Scanner(System.in);
static Random rand = new Random();
public static void main (String[] args)
{
System.out.println("Jarvis Algorithm Test\n");
boolean i = true;
while(i){
System.out.println("SELECT:");
System.out.println("RANDOM:");
System.out.println("USER INPUT:");
System.out.print(":");
// String comm = scan.nextLine();
String comm = "random";
comm = comm.toLowerCase();
if(comm.equals("random")){
randomize();
i = false;
}
else if(comm.equals("user input")){
userinput();
}
else{
System.out.println("INVALID");
}
System.out.println("");
}
Jarvis j = new Jarvis();
j.convexHull(points);
}
public static void randomize(){
int p = 10; //= askpoints();
points = new Point[p];
for(int i = 0; i<p; i++){
points[i] = new Point();
points[i].x = rand.nextInt(300) + 20 ;
points[i].y = rand.nextInt(300) + 20 ;
System.out.println(points[i].x+ " " +points[i].y);
}
}
public static void userinput(){
int n = askpoints();
points = new Point[n];
System.out.println("Enter "+ n +" x, y cordinates");
for (int i = 0; i < n; i++)
{
points[i] = new Point();
points[i].x = scan.nextInt();
points[i].y = scan.nextInt();
}
}
public static int askpoints(){
System.out.print("how many points:");
int i = scan.nextInt();
return i;
}
}
here is my jarvis code
/**
** Java Program to Implement Jarvis Algorithm
* http://www.sanfoundry.com/java-program-to-implement-jarvis-algorithm/
**/
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Arrays;
import javax.swing.JFrame;
/** Class point **/
class Point
{
int x, y;
}
/** Class Jarvis **/
public class Jarvis extends JFrame{
public ArrayList<Integer> x = new ArrayList<Integer>();
public ArrayList<Integer> y = new ArrayList<Integer>();
private boolean CCW(Point p, Point q, Point r)
{
// int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
// if (val >= 0)
// return false;
// return true;
return (q.y - p.y) * (r.x - p.x) < (r.y - p.y) * (q.y - p.x);
}
public void convexHull(Point[] points){
int n = points.length;
int[] next = new int[n];
int[] prev = new int[n];
Arrays.fill(next, -1);
int l = 0;
for(int i =1; i<n;i++){
if(points[i].x < points[l].x){
l = i;
}
}
System.out.println(points[l].x);
int p = l;
int q;
do{
q = p + 1;
for(int i = 0;i<n;i++){
System.out.println(CCW(points[p],points[i],points[q]));
if( p!=i &&CCW(points[p],points[i],points[q])){
q = i;
}
next[p] = q;
prev[q] = p;
p = q;
}
}while(p == l);
}
/*
* display(points, next);
*/
}
i tried to print the values of next to know the indexes however the values are all 0. so i tried printing what CCW returns and it always returns false. why is that i followed the algorithm in the link.
any tips?

Related

What is wrong with my solution of SPOJ ACTIV?

Here is the link for the problem:SPOJ - ACTIV
I came up with the recurrence for the problem as:
F(i) = 1+F(i+1)+F(next(activities[i].endtime))
where next() finds out the index of the activity with start time>= end time of the current activity, while the activities have been sorted in increasing order of their Start time.
This is my java solution, although it passes many test cases of SPOJ toolkit, however it does give WA for some. What is the problem in my concept/solution?
import java.util.*;
import java.io.*;
class Pair<T>{
final T x;
final T y;
Pair(T a, T b){
this.x = a;
this.y = b;
}
}
public class Activities{
private static int search(Pair<Integer> []p,int key, int l, int h)
{
int ll=l;
while(l<h)
{
int mid = (l+h)/2;
if(p[mid].x < key)l=mid+1;
else if(p[mid].x == key){
while(mid>=ll && p[mid].x == key)mid--;
return mid+1;
}
else h=mid;
}
if(l==h && l>=0 && p[l].x>=key)return l;
return -1;
}
public static void main(String[] args)throws IOException {
final long mod = 100000000;
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
int n = Integer.parseInt(buff.readLine());
if(n==-1)return;
Pair <Integer> p [] = new Pair[n];
for(int i=0;i<n;i++){
String [] in = buff.readLine().split(" ");
int x = Integer.parseInt(in[0]), y = Integer.parseInt(in[1]);
p[i] = new <Integer>Pair(x,y);
}
Arrays.sort(p, new Comparator<Pair<Integer>>(){
public int compare(Pair<Integer> p1, Pair<Integer> p2){
if(p1.x == p2.x)return p1.y - p2.y;
else return p1.x - p2.x;
}
});
long dp[] = new long[n];
dp[n-1] = 1;
for(int i=n-2;i>=0;i--)
{
int idx = search(p,p[i].y,i,n-1);
dp[i] = 1+dp[i+1];
if(idx != -1)dp[i]=dp[i]+dp[idx];
}
String res = (dp[0]%mod)+"";
while(res.length()<8)res = '0'+res;
System.out.println(res);
}
}
}
Your code is able to exceed a long type scope. You should perform your calculation with more frequent casting to the [0, mod) range. This should be enough to fix your issue and solve this Spoj's problem:
for(int i=n-2;i>=0;i--)
{
int idx = search(p,p[i].y,i,n-1);
dp[i] = 1+dp[i+1]%mod;
if(idx != -1)dp[i]=(dp[i]%mod+dp[idx]%mod)%mod;
}

closest pair of points, recursion not stopping at the correct area

Working on a closest point algorithm here. I am taking a 2d array of ints in. For some reason I am not getting the right answer. What is wrong with my recursion in conquer? I think that is the problem.
package ClosestPair;
import java.awt.Point;
import java.util.Arrays;
public class ClosestPair{
public double divide(int[][] data){
int size = data.length;
int[][] X_L = new int[size/2][2];
int[][] X_R = new int[size/2][2];
int[][] Y_L = new int[size/2][2];
int[][] Y_R = new int[size/2][2];
int[][] P_L = new int[size][2];
int[][] P_R = new int[size][2];
////////// X Portion ////////////////////////////
//sort the points
int[][] temp = data;
Arrays.sort(temp, new ColumnComparator(0));
//split the points
for (int i = 0; i < temp.length/2; i++){
X_L[i][0] = temp[i][0];
X_L[i][1] = temp[i+1][1];
X_R[i][0] = temp[i+temp.length/2][0];
X_R[i][1] = temp[i+temp.length/2][1];
}
////////// Y Portion ////////////////////////////
Arrays.sort(temp, new ColumnComparator(1));
//split the points
for (int i = 0; i < temp.length/2; i++){
Y_L[i][0] = temp[i][0];
Y_L[i][1] = temp[i+1][1];
Y_R[i][0] = temp[i+temp.length/2][0];
Y_R[i][1] = temp[i+temp.length/2][1];
}
//P_L
P_L= appendArrays(X_L, Y_L);
//P_R
P_R= appendArrays(X_R, Y_R);
if(conquer(P_L)< conquer(P_R)) return conquer(P_L);
return conquer(P_R);
}
public double conquer(int[][] array){
if(array.length == 2){
return distance(array);
}
int[][] temp1 = new int[array.length/2][2];
int[][] temp2 = new int[array.length/2][2];
int length = array.length/4;
for (int i = 0; i < length; i++){
temp1[i][0] = array[i][0];
temp1[i][1] = array[i+1][1];
temp2[i][0] = array[i+array.length/2][0];
temp2[i][1] = array[i+array.length/2][1];
}
return conquer(temp1);
}
private static int[][] appendArrays(int[][] array1, int[][] array2) {
int[][] ret = new int[array1.length + array2.length][];
int i = 0;
for (;i<array1.length;i++) {
ret[i] = array1[i];
}
for (int j = 0;j<array2.length;j++) {
ret[i++] = array2[j];
}
return ret;
}
public double distance(int[][] points){
//pair distance
int a = (points[0][0]+points[1][0]);
int b = (points[1][1]+points[1][1]);
return Math.sqrt( Math.pow(a, 2) + Math.pow(b, 2) );
}
}
You have wrong formula for calculation distance. It should be
int a = (points[0][0]-points[1][0]);
int b = (points[1][1]-points[1][1]);
return Math.sqrt( Math.pow(a, 2) + Math.pow(b, 2) );
Or you could use special function:
int x = (points[0][0]-points[1][0]);
int y = (points[1][1]-points[1][1]);
return Math.hypot(x,y);

How to find brightest spot in a 2D array of numbers

I'm trying to figure out how to go about using these methods to complete this assignment but I'm still relatively new with Java and don't know where to go with it. The array file we have is: 2D Array
Here is the assignment: Assignment
I am just looking for some insight on the math and what to use to get started with these methods. I'm not asking for anyone to do my homework! Thanks for any help in advance!
Here is what I have so far:
public static void main(String[] args) throws FileNotFoundException {
File skyimage = new File("skyimage.txt");
Scanner scan = new Scanner(skyimage);
int r, c;
r = scan.nextInt();
c = scan.nextInt();
int sky[][] = new int[r][c];
for(r = 0; r < sky.length; r++){
for(c = 0; c < sky[r].length; c++)
sky[r][c] = scan.nextInt();
}
printArray(sky);
lightSource(sky, c);
}//end main
private static void printArray(int[][] sky) {
for(int r = 0; r < sky.length; r++){
for(int c = 0; c < sky[r].length; c++){
System.out.printf("%5d", sky[r][c]);
}
System.out.println();
}
}
public static void lightSource(int sky[][], int n){
Point[] lightPoint = new Point[n];
for(int r = 0; r < sky.length; r++){
for(int c = 0; c < sky[r].length; c++){
new Point(r, c);
}
}
System.out.println("The brightest interior point is located at: " + lightPoint);
}//end method
public static void darkSource(){
}//end method
public static void filterImage(){
}//end method
public static void negativeImage(){
}//end method
Once you have read the input, all you need is just a few utility methods
(like sum, getNeighbours and isValidPoint) and a few loops.
Here is a sketch (not a full-blown solution).
In it I have hard-coded the sample sky input.
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
public class Test045 {
private static int[][] sky = {
{10,2,2},
{10,5,1},
{1,2,2}
};
public static void main(String[] args) {
Point min = null;
Point max = null;
Integer sumMin = null;
Integer sumMax = null;
Integer s = null;
for (int i=0; i<sky.length; i++){
for (int j=0; j<sky[0].length; j++){
s=sum(getNeighbours(i, j));
if (sumMin==null || sumMin > s){
min = new Point(i,j);
sumMin = s;
}
if (sumMax==null || sumMax < s){
max = new Point(i,j);
sumMax = s;
}
}
}
System.out.println("Max Light at: " + max.x + ", " + max.y +
" ; MAX Light = " + sumMax);
System.out.println("Min Light at: " + min.x + ", " + min.y +
" ; MIN Light = " + sumMin);
}
private static int sum(List<Point> lst){
int sum = 0;
for (Point p : lst){
sum += sky[p.x][p.y];
}
return sum;
}
private static List<Point> getNeighbours(int ip, int jp){
List<Point> lst = new ArrayList<Point>();
for (int i=-1; i<=1; i++){
for (int j=-1; j<=1; j++){
if (isValidPoint(ip+i, jp+j)){
lst.add(new Point(ip+i, jp+j));
}
}
}
return lst;
}
private static boolean isValidPoint(int i, int j){
return
i >= 0 && i < sky.length &&
j >= 0 && j < sky[0].length;
}
}

Java: Count Inversions Algorithm logic went wrong

I am trying to write the Count inversion algorithm. It works on an array of size 10. However, things went terribly wrong, when I tried to test on an array of size 100000. I was still able to sort the array but the number of inversions is NEGATIVE, which is wrong. I don't understand which part of my logic went wrong.
My main logic: I created an array object called myArray and it has a CountSplitInv instance method that is suppose to sort the sub-arrays and return number of inversions involved.
Please help me out. I have been stuck in this for a long time now and I still wasn't able to figure out what went wrong.
I have a feeling that I don't understand Recursion concept fully.
import java.io.*;
import java.util.*;
import java.math.*;
class myArray{
private int[] input_array;
private int nElems;
public myArray(int max){
input_array = new int[max];
nElems = 0;
}
public void insert(int value){
input_array[nElems++] = value;
}
public void display(){
for(int j = 0; j < nElems; j++){
System.out.print(input_array[j] + " ");
}
System.out.println("");
}
public void SortAndCount(){
int[] output_array = new int[nElems];
int ans = SortNInversionCounts(output_array,0, nElems -1);
System.out.println("number of inversions IS: " + ans);
}
public int SortNInversionCounts(int[] output_array, int lowerBound, int upperBound){
if(lowerBound == upperBound){
return 0;
} else{
int mid = (lowerBound + upperBound)/2;
int x, y , z;
x = SortNInversionCounts(output_array, lowerBound, mid);
y = SortNInversionCounts(output_array, mid+1, upperBound);
z = CountSplitInv(output_array, lowerBound, mid+1, upperBound);
return x + y + z;
}
}
public int CountSplitInv(int[] output_array, int lowPtr, int highPtr, int upperBound){
int j = 0;
int lowerBound = lowPtr;
int mid = highPtr - 1;
int n = upperBound - lowerBound + 1;
int numOfInversions = 0;
while(lowPtr <= mid && highPtr <= upperBound){
if( input_array[lowPtr] < input_array[highPtr]){
output_array[j++] = input_array[lowPtr++];
} else{
output_array[j++] = input_array[highPtr++];
// WHERE I count number of inversions
numOfInversions = numOfInversions + (mid - lowPtr + 1);
}
}
while(lowPtr <= mid){
output_array[j++] = input_array[lowPtr++];
}
while(highPtr <= upperBound){
output_array[j++] = input_array[highPtr++];
}
for(j = 0; j < n; j++){
input_array[lowerBound+j] = output_array[j];
}
return numOfInversions;
}
}
class NumOfInversionsApp{
public static void main(String[] args) throws IOException{
// Read input file
FileInputStream fil = new FileInputStream("IntegerArray.txt");
BufferedReader br = new BufferedReader( new InputStreamReader(fil));
myArray in_array = new myArray(100000);
String element = null;
while( ( element = br.readLine()) != null){
in_array.insert( Integer.parseInt(element) );
}
// input_array.display();
in_array.SortAndCount();
// input_array.display();
}
}

Fibonacci sequence in Java using for statements

I tried making a Java program executing the Fibonacci sequence.
Here's my code:
import java.io.*;
public class Fibonacci{
public static void main(String[]args){
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int ctr1=0;
int ctr2=0;
int num1=0;
int num2=0;
int num3=0;
try{
System.out.println("How many numbers would you want to see?");
ctr2=Integer.parseInt(Data.readLine());
for(int ans=0; ctr1==ctr2; ctr1++){
num1++;
System.out.println(num2 + "\n" + num1);
ans=num1+num2;
System.out.println(ans);
ans=num3;
}
}catch(IOException err){
System.out.println("Error!" + err);
}catch(NumberFormatException err){
System.out.println("Invald Input!");
}
}
}
Obviously, I'm a beginner in Java and I don't know how to properly use the for statement. Would somebody be kind enough to make my code work? Or maybe make a way shorter code that works. I'm a beginner so be cool. Thanks :)
Fibonacci series in java is actually quite simple and can be done with just one single for-loop!!!!
import java.io.*;
class fibonacci{
public static void main() throws NumberFormatException, IOException{
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int a,b,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=Integer.parseInt(Data.readLine());
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
This has been done using buffered reader........ If you are said to use only bufferedreader go for this else you can use Scanner class which is much simple and easy to use because you don't have to catch or throw any exceptions.....
Scanner program:-
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a,b,c;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
Now as I said in one loop you can do it.... Here is another method where you do the swapping inside the body of the loop and not in the arguments of it...
And this is much simplier to understand for beginners as u don't have to pass multiple variables inside the arguments and yeah its a bit longer
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a = 0,b = 1,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
System.out.println(a +"\n" +b);//\n is used to go to next line....
for (c=0;c<d;c++){
c = a + b;//Doing and printing the fibonacci...
System.out.println(c);
a = b;
b = c;//Swapping the values...
}
}
}
So here i have given you three methods that should give the same output(Most probably) choose whichever is convenient for you..
Look at this code snippet which is much easier than yours to understand. Solution tip is simple, you keep 2 pointers for the first 2 fibonacci numbers and update them appropriately in the loop. In the example below, the loop executes 10 times, you can modify it as desired.
static void fibonacci() {
int ptr1 = 1, ptr2 = 1;
int temp = 0;
System.out.print(ptr1 + " " + ptr2 + " ");
for (int i = 0; i < 10; i++) {
System.out.print(ptr1 + ptr2 + " ");
temp = ptr1;
ptr1 = ptr2;
ptr2 = temp + ptr2;
}
}
Output:
1 1 2 3 5 8 13 21 34 55 89 144
Expanding on the answers, if you want to look really cool use recursion.
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int N = 300; // how many numbers you want to generate
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fib(i));
}
}
Here is Google search of what it is, hope those resources help: http://bit.ly/1cWxhUS
I'm a beginner in java as well however I've found an easy way to create a Fibonacci number using an array. The basic principle of a Fibonacci number is the addition of the current number and the number that came before.
Here is my code:
//Creation of array
int [ ] fib = new int[size];
//Assigning values to the first and second indexes of array named "fib"
fib [0] = 0;
fib [1] = 1;
//Creating variable "a" to use in for loop
int a = 1
//For loop which creates a Fibonacci number
for( int i = 2; i < size ; i++)
{
fib[i] = a;
a = fib[i] + fib[i-1];
}
This is another algorithm which I found online and I kind of simplified the code from it.
public static BigInteger fib(BigInteger x) {
if (x.intValue() < 0){return x.intValue() % 2 == 0 ?fib(x.multiply(BigInteger.valueOf(-1))).multiply(BigInteger.valueOf(-1)) : fib(x.multiply(BigInteger.valueOf(-1)));}
int n = Integer.valueOf(x.toString());
BigInteger a = BigInteger.ZERO,b = BigInteger.ONE;
for (int bit = Integer.highestOneBit(n); bit != 0; bit >>>= 1) {
BigInteger d = a.multiply(b.shiftLeft(1).subtract(a));
BigInteger e = a.multiply(a).add(b.multiply(b));
a = d;
b = e;
if ((n & bit) != 0) {
BigInteger c = a.add(b);
a = b;
b = c;
}
}
return a;
}
I know there is a chance that you wont understand how to use BigInteger, so I am giving you this link, just trying to be helpful.
Here we get Fibonacci Series up to n.
public static void fibSequence(int n) {
int sum = 0;
for (int x = 0, y = 1; sum < n; x = y, y = sum, sum = x + y) {
System.out.print(sum + " ");
}
}
Example:
Input: n = 20
Output: 0 1 1 2 3 5 8 13
more simple way
public static void main(String[] args) {
int first = 1;
int second = 2;
for (int i = 0; i < 20; i++) {
if (i == 0)
System.out.print(first);
System.out.print("," + second);
int temp = second;
second = first + second;
first = temp;
}
}```
program output :: 1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946
import java.util.*;
public class sequence1
{
public static void main(String[] args)
{
sequence1 fs=new sequence1();
fs.fibonacci();
}
public void fibonacci()
{
int numb1 = 1;
int numb2 = 1;
int temp = 0;
#SuppressWarnings("resource")
Scanner input=new Scanner(System.in);
System.out.println("How Many Terms? (Up To 45)");
int x=input.nextInt();
x=x-2;
System.out.println(numb1);
System.out.println(numb2);
for (int i = 0; i < x; i++)
{
System.out.println(numb1 + numb2 + " ");
temp = numb1;
numb1 = numb2;
numb2 = temp + numb2;
}
}
}
This function return the fibonacci series
/**
* #param startElement
* #param secondElent
* #param length :length of fibonacci series
* #return fibonacciseries : contain the series of fibonacci series
*/
public int[] createFibonacciSeries(int startElement, int secondElent,
int length) {
int fibonacciSeries[] = new int[length];
fibonacciSeries[0] = startElement;
fibonacciSeries[1] = secondElent;
for (int i = 2; i < length; i++) {
fibonacciSeries[i] = fibonacciSeries[i - 1]
+ fibonacciSeries[i - 2];
}
return fibonacciSeries;
}
import java.util.*;
class MyFibonacci {
public static void main(String a[]){
int febCount = 15;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i < febCount; i++){
feb[i] = feb[i-1] + feb[i-2];
}
for(int i=0; i< febCount; i++){
System.out.print(feb[i] + " ");
}
}
}
public class FibonacciExercitiu {
public static void main(String[] args) {
int result = fib(6); //here we test the code. Scanner can be implemented.
System.out.println(result);
}
public static int fib(int n) {
int x = 1;
int y = 1;
int z = 1; //this line is only for declaring z as a variable. the real assignment for z is in the for loop.
for (int i = 0; i < n - 2; i++) {
z = x + y;
x = y;
y = z;
}
return z;
}
/*
1. F(0) = 1 (x)
2. F(1) = 1.(y) =>Becomes x for point4
3.(z)F(2) = 2 (z) =>Becomes Y for point4 // becomes X for point 5
4.(z)F(3) = 3 // becomes y for point 5
5.(z)F(4) = 5 ..and so on
*/
}
public static int[] fibonachiSeq(int n)
{
if (n < 0)
return null;
int[] F = new int[n+1];
F[0] = 0;
if (n == 0)
return F;
F[1] = 1;
for (int i = 2; i <= n; i++)
{
F[i] = F[i-1] + F[i-2];
}
return F;
}
Using while loop
class Feb
{
static void Main(string[] args)
{
int fn = 0;
int sn = 1;
int tn = 1;
Console.WriteLine(fn);
Console.WriteLine(sn);
while (true)
{
tn = fn + sn;
if (tn >10)
{
break;
}
Console.WriteLine(tn);
fn = sn;
sn = tn;
}
Console.Read();
}
}
public class Febonacci {
public static void main(String[] args) {
int first =0;
int secend =1;
System.out.print(first+","+secend);
for (int k=1;k<7;k++){
System.out.print(","+(first+secend ));
if(k%2!=0)
first+=secend;
else
secend+=first;
}
}
}
public class FibonacciSeries {
public static void main(String[] args) {
int a=0, c=0, b=1;
for(int i=0; i<10; i++) {
System.out.print(c+" ");
a = c + b;
c = b;
b = a;
}
}
}

Categories

Resources