Mergesort Hull using Java - java

I have a class Hull that has one method call update:
public void update(String input) {
String[] array = input.split(" ");
int xCoordinate1= Integer.parseInt(array[0]);
int xCoordinate2 = Integer.parseInt(array[1]);
int yCoordinate = Integer.parseInt(strArr[2]);
String newline = System.getProperty("line.separator");
System.out.println(newline + input);
}
My mainclass page has MergeHulls and main method as such:
public static Hull mergeHulls(Hull hull1, Hull hull2) {
int a=0;
int b=0;
ArrayList<Hull> array1 = new ArrayList<Hull>();
ArrayList<Hull> array2 = new ArrayList<Hull>();
ArrayList<Hull> finalArray = new ArrayList<Hull>();
return (not sure);
}
I roughly do know how to implement the method but am unsure how to get it in the codes. I will write the psudeo code and if someone can help me see if this is correct and how to go about doing it.
int a = 0
int b = 0
While (both arraylists are not null)
{
if (hull1a <= hull2b)
{
then append hull1a to finalarray and increment i
}else
{
append hull2b to finalarray and increment j
}
Question here is if I have a collection of three coordinates in my hull as such:
(0,1,2)
(1,2,3)
(2,3,4)
How do I compare the second x coordinate of the previous interval and with the first x coordinate of the current interval and sort and merge them together?
Please teach me or help me with some references. Really appreciate it.

Related

Method doesn't work

For my assignment, I have to use methods to find the number of patterns in an array. The pattern is counted when the sum of adjacent numbers in an array is more than 7.
I have to use 2 methods, 1 being insertNumbers to create an array and another being computePattern to count the patterns.
However, the pattern printed out doesn't match the array printed out. Here is the code.
As this is an assignment, I would rather not get answers but answers on which part of my code is wrong, and how do I fix it.
EDIT: Here is a sample output.
Sample output #1: Array: 2 7 2 3 1 5 7 4 3 6
Number of patterns: 3
public static int[] insertNumbers()
{
//Declaring the array.
int randomArray[] = new int[10];
//Setting random numbers into the array.
for (int k = 0;k < randomArray.length;k++)
{
int i = (int)((Math.random()*9)+1);
randomArray[k] = i;
}
//Returning array into other methods.
return randomArray;
}
public static int computePattern()
{
int a = 0;
int b = 1;
int pattern = 0;
int[] randomArray = insertNumbers();
//Computing the number of patterns.
for (;a<=8 && b<=9;)
{
if (randomArray[a] + randomArray[b]>7)
{
pattern++;
}
a+=2;
b+=2;
}
return pattern;
}
public static void main(String[] args)
{
int pattern = computePattern();
int[] randomArray = insertNumbers();
//Printing out the contents of the array.
System.out.print("Array : " );
for(int i = 0; i < 10; i++)
{
System.out.print(+randomArray[i] +" ");
}
System.out.println(" ");
//Printing out the number of patterns.
System.out.println("Number of patterns: "+pattern);
}
You are computing pattern for a different array, and in main you are printing different array (you are calling insertNumbers twice basically). See here:
int pattern = computePattern(); // First time computePatter generates one array
int[] randomArray = insertNumbers(); // Another array is generated here
Also, doesn't seem your pattern counting is correct. Hint: does it compare elements with indexes 1 and 2?
Remove this line from your main function
int[] randomArray = insertNumbers();
You are calling the function insertNumbers again after computing the pattern.
You should do the compute pattern part this way
{
int a;
int pattern = 0;
int[] randomArray = insertNumbers();
//Computing the number of patterns.
for (a=1;a<9;a++)
{
if (randomArray[a] + randomArray[a-1]>7)
{
pattern++;
}
}
return pattern;
}
And you definitely calling insertNumbers Twice. You should call it once in main and send that array to computePattern.
int[] randomArray = insertNumbers();
int pattern = computePattern(randomArray);

How to find all possible numbers with a Recursion method

i want to write a Recursion method that prints all possible arrangements for these
numbers , the integers 1 to 9
arranged randomly in a grid of three rows and three column.for example :
6 2 1
5 4 7
3 9 8
sorry i don't have any code , because it's very hard to me.
public class Test {
public static void main (String[] args){
String x = "123456789";
System.out.println(test(x,0));
}
public static String test(String x , int y){
if(x.length()==1)return "";
return x.charAt(y)+test(x.substring(y),y);
}
There are many ways to implement something like this, this is one example. I will use int[] instead of String for convenience sake:
public static void main(String[] args) {
nextPermutation(new int[9], 0, new boolean[9]);
}
public static void nextPermutation(int[] perm, int index, boolean[] alreadyUsed) {
if(index == perm.length) {
//the permutation is complete
//you can store it or print it
} else {
for(int i = 0 ; i < alreadyUsed.length ; i++) {
if(alreadyUsed[i]) continue;
perm[index] = i+1;
boolean[] newAlreadyUsed = Arrays.copyOf(alreadyUsed, alreadyUsed.length);
newAlreadyUsed[i] = true;
nextPermutation(Arrays.copyOf(perm, perm.length), index+1, Arrays.copyOf(newAlreadyUsed, newAlreadyUsed.length));
}
}
}
This will generate all possible combinations of 1-9. The idea of the algorithm is that you keep track of which digits you already used, run through a loop and select all available digits.
Note that it's important to pass copies of perm and alreadyUsed, otherwise you will just pass the same array and overwrite previous permutations.
pass values ​​to an array, randomize and create a loop to generate the matrix.
loop: make a generic loop starting to generate matrix with i0 , j0 like position i1 , j1 of matrixand add the values of array
int j = 0;
for( int i = 0; i <= YOURARRAY.length(); i++)
{
System.out.println( i POSITIONOFARRAY );
j+1
}

Dynamic variables

I'm tring to assign variables dynamically, but I don't have a clue how to do that.
What my program should do:
"Write a program to have the user enter three lengths of sides and determine whether the figure is a triangle or not."
This is what I have so far:
package triangle;
import javax.swing.JOptionPane;
public class Triangle {
public static void main(String[] args) {
String x = JOptionPane.showInputDialog("Please enter the side lengths of a triangle with each side \nseparated with a ',' and without spaces. (eg. 1,2,3)");
x += ",";
int y = -1, a = 0;
double z;
for(int i = 0; i < x.length(); i++)
{
if(x.charAt(i) == ',')
{
z = Double.parseDouble(x.substring((y + 1), i));
y = i;
a += z;
}
}
}
}
What I would love to do would be to have this in the if statement:
int a++;
z(a) = Double.parseDouble(x.substring((y + 1), i));
But as I have found out this will not work and I need some kind of array. Sadly, my online class has not started arrays yet and I haven't gotten a grasp of them yet in my own learning.
I would like to make 3 variables (z1, z2, z3) and assign an integer to each one within the if statement.
Edit:
Here's some revised code that now works how I wanted now. Hope this helps someone else in the future!
package triangle;
import javax.swing.JOptionPane;
public class Triangle {
public static void main(String[] args) {
String x = JOptionPane.showInputDialog("Please enter the side lengths of a triangle with each side \nseparated with a ',' and without spaces. (eg. 1,2,3)");
x += ",";
int y = -1, a = 0;
Double[] z = new Double[3];
for(int i = 0; i < x.length(); i++)
{
if(x.charAt(i) == ',')
{
z[a] = Double.parseDouble(x.substring((y + 1), i));
y = i;
a++;
}
}
//Some test code to see if it was working
System.out.println(z[0]);
System.out.println(z[1]);
System.out.println(z[2]);
}
}
You don't need to use arrays, especially that you haven't been introduced to them. You can simply use a Scanner class, and do something similar to
Scanner in = new Scanner(System.in); // this will read from the standard system input
System.out.println("Please enter three lengths of sides: ");
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
And write some logic (I guess that's the point of your homework) checking if this figure is a triangle.
In case you would like to use arrays , you could declare one by doing:
int[] sidesLenghtsArray = new int[3];
And then instead of refering to three different int variables, you could simply refer to your array elements:
int[0] = in.nextInt();
int[1] = in.nextInt();
int[2] = in.nextInt();
Just remember - the number in the brackets is the number of elements that your array will have, but refering to that elements, you start counting from 0. That's why we start with int[0] (1st element) and end with int[2] (3rd element).
Java does not support tuple assignment like
def (a,b,c) = "1,2,3".split(",")
It is possible to do this in Java 8 with a following code:
int[] abc = Arrays.stream("1,2,3".split(",")).mapToInt(Integer::parseInt).toArray();
Here, a would be abc[0], b is abc[1].
Similar code in Java 7 could be this:
String[] abc = "1,2,3".split(",");
int a = Integer.parseInt(a[0]);
int b = Integer.parseInt(a[1]);
int c = Integer.parseInt(a[2]);
The very basic idea is that in every triangle when you add the lengths of two sides, the resulting length should be greater than the length of the remaining sides. Let's say a, b, c are the sides of the triangle.
public static void main(String[] args){
int a=3, b=4, c=5;
if(a+b > c && a+c>b && c+b>a){
System.out.println("This is a valid trianlge");
}
else{
System.out.println("This is not a valid triangle");
}
}
make sure you replace the values of a,b, and c with the values you gain from user input.

How to switch int sort to String sort?

I have written some code for sorting random integers that a user inputted. How would I switch this into sorting randomly inputted letters? Aka, user inputs j, s, g, w, and the programs outputs g, j, s, w?
for (int i = 0; i < random.length; i++) { //"random" is array with stored integers
// Assume first value is x
x = i;
for (int j = i + 1; j < random.length; j++) {
//find smallest value in array (random)
if (random[j] < random[x]) {
x = j;
}
}
if (x != i) {
//swap the values if not in correct order
final int temp = random[i];
random[i] = random[x];
random[x] = temp;
}
itsATextArea.append(random[i] + "\n");// Output ascending order
}
Originally I hoped (though I knew the chances of me being right were against me) that replacing all the 'int' with 'String' would work...naturally I was wrong and realized perhaps I had to list out what letter came before which by using lists such as list.add("a"); etc.
I apologize if this seems like I am asking you guys to do all the work (which I'm not) but I'm not entirely sure how to start going about this, so if anyone can give some hints or tips, that would be most appreciated!
You could use String.compareTo() to do that:
Change this:
int[] random = new int[sizeyouhad];
...
if (random[j] < random[x]) {
...
final int temp = random[i];
to:
String[] random = new String[sizeyouhad];
...
if (random[j].compareTo(random[x]) < 0) {
...
final String temp = random[i];
Trial with your code:
String[] random = new String[3];
random[0] = "b";
random[1] = "c";
random[2] = "a";
int x = 0;
//"random" is array with stored integers
for (int i = 0; i < random.length; i++) {
// Assume first value is x
x = i;
for (int j = i + 1; j < random.length; j++) {
//find smallest value in array (random)
if (random[j].compareTo(random[x]) < 0) {
x = j;
}
}
if (x != i) {
//swap the values if not in correct order
final String temp = random[i];
random[i] = random[x];
random[x] = temp;
}
System.out.println(random[i] + "\n");// Output ascending order
}
If you're just trying to sort a list of strings you should probably use the java.util.Collections.sort method rather than writing your own sorting routine.
Was random originally int[]? If you had changed this to String[], you can use String#compareTo method to discern if one string is "less than" another.
Incidentally, you can change the type of random to Comparable[] and then you can use the same algorithm to sort any object whose class implements the interface!
Try to use Collections.sort() function
List<String> l = Arrays.asList("j","s", "g","w");
Collections.sort(l);
If you consider every character to be a code point[1] and you want to sort by Unicode code point order[2], then there is really no need to change your logic. The work is converting from whatever input you are given (String, char[], etc.) into an int[] of the code points.
[1] - http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#codePointAt(int)
[2] - http://en.wikipedia.org/wiki/Code_point
You can make your code work on any type of Object by using generics.
The following code is very simple and works perfectly (With this library you can solve your problem in few lines):
import static ch.lambdaj.Lambda.sort;
import static ch.lambdaj.Lambda.on;
import java.util.Arrays;
import java.util.List;
public class Test{
public static void main(String[] args) {
List<String> list = Arrays.asList("1","102","-50","54","ABS");
List<String> newList = sort(list, on(String.class));
System.out.println(newList);//[-50, 1, 102, 54, ABS]
}
}
This code uses lambda library (download here, website). Find in the website this example:
List<Person> sorted = sort(persons, on(Person.class).getAge());

Count how many times an element occurs in an array - Java

I recently made a very simple practice program in Python, that takes user input and rolls dice. The code is:
import random
import sys
import math
def roll(rolls, sides, results):
for rolls in range(1, rolls + 1):
result = random.randrange(1, sides + 1)
print result
results.append(result)
def countf(rolls, sides, results):
i = 1
print "There were", rolls, "rolls."
for sides in range(1, sides + 1):
if results.count(i) != 1:
print "There were", results.count(i), i,"s."
else:
print "There was", results.count(i), i
i = i + 1
if i == sides:
break
rolls = input("How many rolls? ")
sides = input("How many sides of the die? ")
results = []
roll(rolls, sides, results)
countf(rolls, sides, results)
(actually this is part of a larger program, so I had to cut'n'paste bits, and I might have missed something out).
And so I decided to translate that to Java. Notice the algorithm here: get random number, print it, append it to an array, then count the amount of each number in the array at the end, and print out that value. Problem is, I don't know how to do the equivalent of someArray.count(someIndex) in Java syntax. So my Java program looks like this so far:
import java.util.*;
public class Dice {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random();
int[] results = new int[TIMES_TO_ROLL];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt(6);
System.out.println(result);
results[i] = result;
}
}
public static int getInt(String prompt) {
System.out.print(prompt + " ");
int integer = input.nextInt();
input.nextLine();
return integer;
}
}
So can someone help me with the array counting code? I understand that this might not be a defined method, since Python is higher level after all, so I could make my own array counting method, but I was wondering if Java, like Python, has a predefined one.
EDIT: I managed something like this:
public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
amt++;
}
else {
amt = amt;
}
}
return amt;
}
EDIT: Just out of interest, assuming I use Command prompt to run my Java program and Python.exe (command prompt console for Python), which one will be faster (in other words, for the same code, which language has better performance?)?
You could use a HashMap to store the result.
If the new number is not in your map you add it with "1" as initial value.
If it exists your put "+1" to the current map value.
To display the values you just have to iterate on you entries in a for each loop.
The solution is to transform your array to a List and then use the Collections.frequency method:
List<Integer> resultList = Arrays.asList(results);
int freq = Collections.frequency(resultList, 4);
Also you could use ArrayList from the very beginning saving you the transformation:
List<Integer> result = new ArrayList<Integer>();
// add results
int freq = Collections.frequency(result, 4);
See the Collections documentation here
EDIT: If performance is an issue (as suggested in the comments) then maybe you want to use each index of the array as a counter, as follows:
Random flip = new Random(SIDES);
int[] counters = new int[SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
counters[result] = counters[result]+1;
}
Notice that you no longer need to count at the end since you've already got all the counters in the array and there is no overhead of calculating the hash.
There are a couple libraries that will do this for you:
Google Guava's MultiSet
Apache Common's Bag
But for something so simple, you may consider an extra library a bit excessive.
You can also do this yourself with an int[]. Assuming your dice is using whole numbers, have the number rolled refer to the index into the array, and then increment the value at that index. When you need to retrieve the value for a given number, look up its value by the index.
private static final int NUMBER_DICE_SIDES = 6;
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random(NUMBER_DICE_SIDES);
int[] results = new int[NUMBER_DICE_SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
System.out.println(result);
results[result]++;
}
for(int i = 0; i < NUMBER_DICE_SIDES; ++i) {
System.out.println((i+1)+"'s: " + arraysCount(results, i));
}
}
public static int arrayCount(int[] array, int item) {
return array[item];
}
There's a frequency method in collections
int occurrences = Collections.frequency(listObject, searchItem);
Java doc for collections
As far as I am aware, there is no defined method to return the frequency of a particular element in an array. If you were to write a custom method, it would simply be a matter of iterating through the array, checking each value, and if the value matches the element you're after, incrementing a counter.
So something like:
// in this example, we assume myArray is an array of ints
private int count( int[] myArray, int targetValue) {
int counter = 0;
for (int i = 0 ; i < myArray.length; i++ ) {
if (myArray[i] == targetValue) {
counter++;
}
}
return counter;
}
Of course, if you want to find the frequency of all the unique values in your array, this has the potential of being extremely inefficient.
Also, why are you using a 7-sided die? The Random nextInt() will return a number from 0 up to but not including the max. So your die will return values from 0 through 6. For a six-sided die, you'd want a new Random(6); and then increment your roll by one to get a value from one through six: flip.nextInt() +1;.
class FindOccurrence {
public static void main (String[]args) {
int myArray[] = {5, 8, 5, 12, 19, 5, 6, 7, 100, 5, 45, 6, 5, 5, 5};
int numToFind = 5;
int numberOfOccurrence = 0;
for (int i=0; i < myArray.length; i++) {
if (numToFind == myArray[i]) {
numberOfOccurrence++;
}
}
System.out.println("Our number: " + numToFind);
System.out.println("Number of times it appears: " + numberOfOccurrence);
}
}

Categories