So I'm creating a hash table with LinkedLists using the multiplication method. As an instance variable I define the LinkedList "T" that I'll be using, and in the constructor of the class I specify the size of T. However, every time I run my Driver testing class, I get NullPointerExceptions on everything I try to reference anything in T[]. Am I overlooking something? I've spent over an hour trying to figure it out.
ChainedHashTable class:
public class ChainedHashTable
{
private LinkedList<Integer>[] T;
private int m;
private double A;
public ChainedHashTable(int n)
{
for (m = 1; m < n; m *= 2);
T = new LinkedList[m];
Random random = new Random();
int s = random.nextInt(Integer.MAX_VALUE);
A = (s * 1.00) / Integer.MAX_VALUE;
}
public void insert(Integer key)
{
T[hash(key)].add(Integer.valueOf(key));
}
public void delete(int key)
{
T[hash(key)].remove(Integer.valueOf(key));
}
public Integer search(int key)
{
int n = T[hash(key)].indexOf(key);
if (n == -1)
return -1;
else
return T[hash(key)].get(n);
}
private int hash(int key)
{
System.out.println((int)(m * ((key * A) % 1)));
return (int)(m * ((key * A) % 1));
}
public void printTable()
{
for (int i = 0; i < T.length; i++)
{
System.out.println("index: " + i + " " + T[i]);
}
}
}
Driver class:
public class Driver
{
public static void main(String[] args)
{
ChainedHashTable test1 = new ChainedHashTable(20);
test1.printTable();
test1.insert(4);
test1.insert(54);
test1.insert(6);
test1.insert(3);
test1.insert(26);
test1.insert(54);
test1.insert(11);
test1.insert(10);
test1.insert(76);
test1.insert(42);
test1.insert(41);
test1.insert(32);
test1.insert(87);
test1.insert(76);
test1.insert(72);
test1.insert(57);
test1.insert(29);
test1.insert(16);
test1.insert(92);
test1.insert(64);
test1.printTable();
}
}
You are creating an array of references to type LinkedList and setting them to their initial state, which is null.
T = new LinkedList[m];
T now is an array of the computed size m. You need to initialize the objects inside of the array.
T = new LinkedList[m];
for (int i = 0; i < m; i++) {
T[i] = new LinkedList<>();
}
Related
I am new to Java and I am trying to build up a set of tuples like this:
Slegs = {<1,2,500> , <2,5,400>, <5,7,850>, <2,3,450>} and etc.
Then, to define other arrays like:
int u [Slegs][G];
for instance :
u[<1,2,500>][1] = 80
u[<2,5,400>][1] = 80
u[<1,2,500>][2] = 65
u[<2,5,400>][2] = 130
and etc.
For this, I have coded as follows:
public class Model {
public static int Y = 7;
public static int K = 42;
public static int G = 3;
class Sleg {
public int i;
public int j;
public double l;
List<Sleg> Slegs = new ArrayList<Sleg>();
Map <Integer, Sleg> slTup = new HAshMap<Integer, Sleg>();
int[][] u = new int [key][G]; /* I want to define and use a key here*/
}
My problem is that I don't know how to add those tuples into the slTup a for loop, and how to assign a key to them so that I can use the key to define the u[key][G]; As well, how to assert / define that i and j are in Y and i !=j in each tuple <i,j,l>;
I would really appreciate if you could instantiate and printout u[key][g], using the given theoretical data above.
I have some code with these following as a requirement. Not sure what this application is all about, but here is my attempt to answer the questions posed:
Problem:
how to add those tuples into the slTup in a for loop
how to assign a key to them so that I can use the key to define the u[key][G];
could instantiate and printout u[key][g]
want to have a map of integers and Slegs like <1,<1,2,500>> and <2,<2,5,400>>, where the integer is the key and I can then use it in: u[Key][G]
how to assert / define that i and j are in Y and i !=j in each tuple .
Note that its not clear about what it means by "assert i and j are in Y". But, i != j can be asserted by throwing a run time exception (see Sleg class code constructor).
The program with possible answers:
import java.util.*;
public class SlegProgram {
private static int key;
public static void main(String [] args) {
// Create some Slegs
List<Sleg> slegs = Arrays.asList(new Sleg(1,2,500), new Sleg(2,5,400), new Sleg(1,2,500), new Sleg(2,5,400));
System.out.println(slegs);
// Create a Sleg Map with keys
Map <Integer, Sleg> slegMap = new HashMap<>();
for (Sleg sleg : slegs) {
slegMap.put(++key, sleg);
}
System.out.println(slegMap);
// Instantiate and printout u [key][G]
for (Map.Entry<Integer, Sleg> entry : slegMap.entrySet()) {
int [][] u = new int [entry.getKey()][Model.G];
System.out.println(Arrays.deepToString(u)); // prints array with initial values: 0
assignValuesToU(u);
}
// Assert i != j in each Sleg
Sleg illegal = new Sleg(1, 1, 90); // This will throw an exception as i and j are equal
}
private static void assignValuesToU(int [][] u) {
for (int i = 0; i < u.length; i++) {
for (int j = 0; j < u[i].length; j++) {
u [i][j] = 80; // 80 or whatever it needs to be
}
}
System.out.println(Arrays.deepToString(u)); // prints array with assigned values
}
}
class Sleg {
private int i;
private int j;
private int k;
public Sleg(int i, int j, int k) {
if (i == j) {
throw new IllegalArgumentException("Invalid sleg parameters: " + Integer.toString(i));
}
this.i = i;
this.j = j;
this.k = k;
}
public String toString() {
return Integer.toString(i) + "-" + Integer.toString(j) + "-" + Integer.toString(k);
}
}
class Model {
public static final int Y = 7;
public static final int K = 42;
public static final int G = 3;
}
Catching the exception:
try {
Sleg illegal = new Sleg(1, 1, 90);
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage()); // This prints something like: Invalid sleg parameters: 1
}
I didn't understand your problem completely, but as per my understanding to implements Slegs = {<1,2,500> , <2,5,400>, <5,7,850>, <2,3,450>} and etc. like List Slegs = new ArrayList(); create separate class like below:
class slegs{
int i, j, k;
slegs(int i, int j, int k){
this.i = i;
this.j = j;
this.k = k;
}
}
You can also add your logic in the class like for assert / define or while creating an instance you can add checks.
Then you can create instance of these class and add them to list (slegs) using slegs.add(s1). To insert it in map just use the instance map.put(key, s1).
First, to use Sleg as a key of the HasMap or HasSet you have to corerctly define hashCode() and equals(). E.g. like this one:
class Sleg {
private final UUID id;
private final int i;
private final int j;
private final double l;
public Sleg(int i, int j, double l) {
id = UUID.randomUUID();
this.i = i;
this.j = j;
this.l = l;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Sleg))
return false;
Sleg sleg = (Sleg)obj;
return i == sleg.i && j == sleg.j && Double.compare(sleg.l, l) == 0;
}
#Override
public int hashCode() {
return Objects.hash(i, j, l);
}
}
Note: this class Sleg is ready to be a key of the HashMap.
Second, you want to assign an unique integer key with each Sleg instance. I could reccomend you to add this id directly into Skeg instance and increment it each time when you create new object:
class Sleg {
private final int id;
private static final AtomicInteger nextId = new AtomicInteger();
public Sleg(int i, int j, double l) {
id = nextId.incrementAndGet();
}
}
I want to time how long my code takes to perform on average over many test runs. In each test run, doWork() performs the work that I want to time. But I also want to checkWork() in each test run without it counting towards the time. I'm going to have many similar Exercise# classes, so I'd like to abstract the testing via a TestInterface. Is my current way a reasonable approach? Or is there a better design pattern / standard approach? Thanks in advance.
#FunctionalInterface
public interface TestInterface {
void test(final int NUM_TESTS);
}
public class TimeTests {
public static void test(TestInterface ti, final int NUM_TESTS, String testName) {
DecimalFormat df = new DecimalFormat("#.####");
long start = System.nanoTime();
ti.test(NUM_TESTS);
System.out.println("DEBUG: " + testName + " took "
+ df.format((System.nanoTime() - start) * 1.0 / NUM_TESTS)
+ " nanoseconds on average for " + NUM_TESTS + " tests");
}
}
public class Exercise1 {
private static final int NUM_TESTS = (int) Math.pow(10, 6);
private static void mainWork(List<Integer> A) {
// do stuff and time it
}
private static void checkWork(List<Integer> A) {
// do stuff but don't count it towards the time
}
public static void main(String[] args) {
TimeTests.test((NUM_TESTS_LOCAL) -> {
for (int i = 0; i < NUM_TESTS_LOCAL; ++i) {
List<Integer> A = new ArrayList<>();
// add random elements to A
mainWork(A);
checkWork(A);
}
}, NUM_TESTS, "Exercise1");
}
}
Okay, I think I managed to put together a decent framework (is this the right word?) for this task. If anybody could chime in to let me know if my approach is any good, I'd really appreciate it.
While my code seems to work fine for my use cases so far, I have a few questions:
In the interface definition of public interface CloneableTestInput<T extends CloneableTestInput<T>>, how is the type template <T extends CloneableTestInput<T> not a circular definition? I'm not sure I fully understand what that type template is saying.
Is there a way to make a generic CloneableList class that implements CloneableTestInput<List>? Currently, I need to make a separate implementation for each Collection type (e.g. ArrayList, LinkedList, ...). Similarly, is it possible to make a generic CloneableSet class that implements CloneableTestInput<Set>?
Thanks in advance :)
Testing Framework
Part I - An interface for test inputs
This allows TimeTests.java to work for generic input types.
public interface CloneableTestInput<T extends CloneableTestInput<T>> extends Cloneable {
T clone();
}
public class CloneableString implements CloneableTestInput<CloneableString> {
public String data;
public CloneableString() {}
public CloneableString(String input) { data = input; }
public CloneableString clone() { return new CloneableString(String.valueOf(data)); }
}
public class CloneableArrayList extends ArrayList implements CloneableTestInput<CloneableArrayList> {
public CloneableArrayList(ArrayList input) {
this.addAll(input);
}
#Override
public CloneableArrayList clone() {
return new CloneableArrayList(this);
}
}
Part II - An interface for timing tests
#FunctionalInterface
public interface TimeTestsInterface<outputType> {
void test(Callable<CloneableTestInput> formInput
, Function<CloneableTestInput, outputType> runAlgorithm
, Function<CloneableTestInput, outputType> getKnownOutput
, BiFunction<outputType, outputType, Boolean> checkResults
, final int NUM_TESTS, String testName);
}
public class TimeTests<outputType> implements TimeTestsInterface<outputType> {
public void test(Callable<CloneableTestInput> formInput
, Function<CloneableTestInput, outputType> runAlgorithm
, Function<CloneableTestInput, outputType> getKnownOutput
, BiFunction<outputType, outputType, Boolean> checkResults
, final int NUM_TESTS, String testName) {
try {
DecimalFormat df = new DecimalFormat("#.####");
long total = 0, start;
for (int i=0; i < NUM_TESTS; ++i) {
CloneableTestInput input = formInput.call();
CloneableTestInput orig_input = input.clone();
start = System.nanoTime();
outputType algorithmResult = runAlgorithm.apply(input);
total += System.nanoTime() - start;
outputType expectedResult = getKnownOutput.apply(orig_input);
assert(checkResults.apply(algorithmResult, expectedResult));
}
System.out.println("DEBUG: " + testName + " took "
+ df.format(total * 1.0 / NUM_TESTS)
+ " nanoseconds on average for " + NUM_TESTS + " tests");
} catch (Exception|AssertionError e) {
System.out.println(e.toString() + " - " + e.getMessage() + " - ");
e.printStackTrace();
}
}
}
Example Usages
Increment a BigInteger (uses CloneableArrayList)
/**
* Problem 6.2 from EPI
* Given an array A of digits encodiing a decimal number D,
* with MSD at A[0]. Update A to hold D + 1.
*/
public class PlusOne {
private static final int NUM_TESTS = (int) Math.pow(10, 5);
private static final int ARR_LENGTH = (int) Math.pow(10, 2);
private static ArrayList<Integer> plusOne(ArrayList<Integer> A) {
int n = A.size() - 1;
A.set(n, A.get(n) + 1);
for (int i = n; i > 0 && A.get(i) == 10; --i) {
A.set(i, 0);
A.set(i-1, A.get(i-1) + 1);
}
if (A.get(0) == 10) {
// Need additional digit up front as MSD
A.set(0,0);
A.add(0,1);
}
return A;
}
private static ArrayList<Integer> randArray(int len) {
ArrayList<Integer> A = new ArrayList<>();
if (len == 0) return A;
Random rgen = new Random();
A.add(rgen.nextInt(9) + 1);
--len;
while (len != 0) {
A.add(rgen.nextInt(10));
--len;
}
return A;
}
public static void main(String[] args) {
Callable<CloneableTestInput> formInput = () -> new CloneableArrayList(randArray(ARR_LENGTH));
Function<CloneableTestInput, ArrayList<Integer>> runAlgorithm =
(input) -> plusOne((ArrayList<Integer>) input);
Function<CloneableTestInput, ArrayList<Integer>> getKnownOutput =
(orig_input) -> {
BigInteger B = new BigInteger(Joiner.on("").join((ArrayList<Integer>) orig_input));
B = B.add(BigInteger.valueOf(1));
ArrayList<Integer> expectedOutput = new ArrayList<>();
while (B.compareTo(BigInteger.valueOf(0)) > 0) {
expectedOutput.add(0, B.mod(BigInteger.valueOf(10)).intValue());
B = B.divide(BigInteger.valueOf(10));
}
return expectedOutput;
};
BiFunction<ArrayList<Integer>, ArrayList<Integer>, Boolean> checkResults = List::equals;
TimeTests<ArrayList<Integer>> algTimer = new TimeTests<>();
algTimer.test(formInput, runAlgorithm, getKnownOutput, checkResults, NUM_TESTS, "PlusOne");
}
}
Can String be rearranged as a palindrome? (uses CloneableString)
public class CanStringBePalindrome {
private static final int INPUT_STRING_LENGTH = (int) Math.pow(10, 2);
private static final int NUM_TESTS = (int) Math.pow(10, 6);
private static boolean canFormPalindromeHash(final String s) {
Map<Character, Integer> charFreqs = new HashMap<>();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (!charFreqs.containsKey(c))
charFreqs.put(c, 1);
else
charFreqs.put(c, charFreqs.get(c) + 1);
}
int oddFreqCount = 0;
for (Map.Entry<Character, Integer> entry : charFreqs.entrySet()) {
if ((entry.getValue() % 2) != 0 && (++oddFreqCount > 1))
return false;
}
return true;
}
private static boolean canFormPalindromeSorting(final String s) {
// TODO : find faster/simpler way of getting frequency counts
char[] a = s.toCharArray();
Arrays.sort(a);
int oddFreqCount = 0;
int numCurrChar =1;
for (int i = 1; i < a.length && oddFreqCount <= 1; ++i) {
if(a[i] != a[i-1]) {
if ((numCurrChar & 1) != 0)
++oddFreqCount;
numCurrChar = 1;
} else
++numCurrChar;
}
if ((numCurrChar & 1) != 0)
++oddFreqCount;
return oddFreqCount <= 1;
}
private static String randString(int len) {
StringBuilder sb = new StringBuilder();
Random rgen = new Random();
while (len-- > 0)
sb.append((char)(rgen.nextInt(26) + 'A'));
return sb.toString();
}
public static void main(String[] args) {
Callable<CloneableTestInput> formInput = () -> new CloneableString(randString(INPUT_STRING_LENGTH));
Function<CloneableTestInput, Boolean > runAlgorithm =
(input) -> canFormPalindromeHash(((CloneableString)input).data);
Function<CloneableTestInput, Boolean> getKnownOutput =
(orig_input) -> canFormPalindromeSorting(((CloneableString)orig_input).data);
BiFunction<Boolean, Boolean, Boolean> checkResults = Boolean::equals;
TimeTests<Boolean> algTimer = new TimeTests<>();
algTimer.test(formInput, runAlgorithm, getKnownOutput, checkResults
, NUM_TESTS, "CanStringBePalindrome");
}
}
I have written a simple genetic algorithm program in java. What it is does is maximize the decimal value represented by the bits in the chromosome. Somehow mutation is not working as expected, e.g. causing two genes to mutate when just one is to change. The print statements I have included there show which to mutate, but in addition to that some more chromosomes get mutated. I can't figure out what the problem is :-(
Here are my java classes.
Gene.java
public class Gene {
private int value;
public Gene() {
value = Math.random() < 0.5 ? 0 : 1;
}
public Gene(int value) {
if (value != 0 && value != 1) {
throw new IllegalArgumentException("value must be either 0 or 1");
}
else {
this.value = value;
}
}
public void mutate() {
value = 1 - value;
}
public int value() {
return value;
}
#Override
public String toString() {
return String.valueOf(value);
}
}
Chromosome.java
import java.util.ArrayList;
import java.util.List;
public class Chromosome implements Comparable {
private ArrayList<Gene> genes;
private final int chromosomeLength;
public Chromosome(int length) {
this.genes = new ArrayList<>();
this.chromosomeLength = length > 0 ? length : 16;
for (int i = 0; i < chromosomeLength; i++) {
this.genes.add(i, new Gene());
}
}
public List<Gene> getAllele(int fromIndex, int toIndex) {
return new ArrayList<>(genes.subList(fromIndex, toIndex));
}
public void setAllele(int fromIndex, List<Gene> allele) {
int lastIndex = fromIndex + allele.size();
if (lastIndex > chromosomeLength) {
throw new IndexOutOfBoundsException("the allele exceeds beyond the size of the chromosome");
}
for (int i = fromIndex, j = 0; i < lastIndex; i++, j++) {
genes.set(i, allele.get(j));
}
}
public int getChromosomeLength() {
return chromosomeLength;
}
public void setGeneAt(int index, Gene gene) {
genes.set(index, gene);
}
public Gene getGeneAt(int index) {
return genes.get(index);
}
public int value() {
return Integer.parseInt(this.toString(), 2);
}
#Override
public String toString() {
StringBuilder chromosome = new StringBuilder("");
genes.stream().forEach((Gene g) -> chromosome.append(g));
return chromosome.toString();
}
#Override
public int compareTo(Object anotherChromosome) {
Chromosome c = (Chromosome) anotherChromosome;
return this.value() - c.value();
}
}
GenePool.java
import java.util.ArrayList;
import java.util.Arrays;
public class GenePool {
private final ArrayList<Chromosome> genePool;
private final int genePoolSize;
private final int chromosomeLength;
private final double crossOverRate;
private final double mutationRate;
private int[] crossPoints;
public GenePool(int numOfChromosome, int chromosomeLength, double crossOverRate, double mutationRate) {
this.genePoolSize = numOfChromosome;
this.chromosomeLength = chromosomeLength > 0 ? chromosomeLength : 16;
this.crossOverRate = crossOverRate;
this.mutationRate = mutationRate;
crossPoints = new int[1];
crossPoints[0] = this.chromosomeLength / 2;
genePool = new ArrayList<>();
for (int i = 0; i < numOfChromosome; i++) {
genePool.add(new Chromosome(chromosomeLength));
}
}
public int getGenePoolSize() {
return genePoolSize;
}
public Chromosome getChromosomeAt(int index) {
return genePool.get(index);
}
public void setChromosomeAt(int index, Chromosome c) {
genePool.set(index, c);
}
public int getChromosomeLength() {
return chromosomeLength;
}
public Chromosome[] crossOver(Chromosome c1, Chromosome c2) {
Chromosome[] offsprings = new Chromosome[2];
offsprings[0] = new Chromosome(c1.getChromosomeLength());
offsprings[1] = new Chromosome(c1.getChromosomeLength());
Chromosome[] parentChromosomes = {c1, c2};
int selector = 0;
for (int i = 0, start = 0; i <= crossPoints.length; i++) {
int crossPoint = i == crossPoints.length ? c1.getChromosomeLength() : crossPoints[i];
offsprings[0].setAllele(start, parentChromosomes[selector].getAllele(start, crossPoint));
offsprings[1].setAllele(start, parentChromosomes[1 - selector].getAllele(start, crossPoint));
selector = 1 - selector;
start = crossPoint;
}
return offsprings;
}
public void mutateGenePool() {
int totalGeneCount = genePoolSize * chromosomeLength;
System.out.println("Mutating genes:");
for (int i = 0; i < totalGeneCount; i++) {
double prob = Math.random();
if (prob < mutationRate) {
System.out.printf("Chromosome#: %d\tGene#: %d\n", i / chromosomeLength, i % chromosomeLength);
genePool.get(i / chromosomeLength).getGeneAt(i % chromosomeLength).mutate();
}
}
System.out.println("");
}
public int getLeastFitIndex() {
int index = 0;
int min = genePool.get(index).value();
int currentValue;
for (int i = 1; i < genePoolSize; i++) {
currentValue = genePool.get(i).value();
if (currentValue < min) {
index = i;
min = currentValue;
}
}
return index;
}
public void saveFittest(ArrayList<Chromosome> offsprings) {
// sort in ascending order
offsprings.sort(null);
offsprings.stream().forEach((offspring) -> {
int leastFitIndex = getLeastFitIndex();
if (offspring.value() > genePool.get(leastFitIndex).value()) {
genePool.set(leastFitIndex, offspring);
}
});
}
public void evolve(int noOfGeneration) {
for (int generation = 1; generation <= noOfGeneration; generation++) {
System.out.println("Generation :" + generation);
ArrayList<Integer> selection = new ArrayList<>();
for (int i = 0; i < genePoolSize; i++) {
if (Math.random() <= crossOverRate) {
selection.add(i);
}
}
if (selection.size() % 2 == 1) {
selection.remove(selection.size() - 1);
}
ArrayList<Chromosome> offsprings = new ArrayList<>();
for (int i = 0; i < selection.size(); i += 2) {
int index1 = selection.get(i);
int index2 = selection.get(i + 1);
offsprings.addAll(Arrays.asList(crossOver(genePool.get(index1), genePool.get(index2))));
}
System.out.println("Before saving the offsprings");
displayChromosomes(genePool, "GenePool");
displayChromosomes(offsprings, "Offsprings");
saveFittest(offsprings);
System.out.println("Before mutation:");
displayChromosomes(genePool, "GenePool");
mutateGenePool();
System.out.println("After mutation:");
displayChromosomes(genePool, "GenePool");
System.out.println("\n\n");
}
}
public void displayChromosomes(ArrayList<Chromosome> geneList, String name) {
System.out.println(name);
if (geneList.isEmpty()) {
System.out.println("Empty list");
}
geneList.stream().forEach((c) -> {
System.out.println(c + " -> " + c.value());
});
System.out.println("");
}
}
GADemo.java
public class GADemo {
public static void main(String[] args) {
GenePool gp = new GenePool(6, 8, 0.25, 0.01);
gp.evolve(10);
}
}
After evolving for a number of generations, the chromosomes all tend to become exactly the same, or very similar. And the problem is that that value is not the maximum for that many bits, and sometimes even a small value. For example, for 8 bits the values should (tend to) approach 255, but this doesn't do so in my code. Someone please provide a hint where/how to look for and solve the problem.
Focus on these lines and imagine the references. These are from setAllele()
for (int i = fromIndex, j = 0; i < lastIndex; i++, j++) {
genes.set(i, allele.get(j));
}
You are basically copying the reference from one onto the other. They are the same Gene so whatever mutation you do on those genes, will also affect even other Chromosomes.
You must produce a deep copy here.
Initially each chromosome has an own list of genes. But when you do the crossover operation you set gene objects from one chromosome into the gene list of other chromosome.
When you evolve the system, the number of shared genes will rise and therefore ultimately all chromosomes will share the same genes. No matter how you mutate a gene the chromosomes are not affected.
EDIT:
As Incognito also answered the setAllele method seems to be the culprit where gene sharing starts. You may want to introduce a method in the gene class where you can set its value given another gene.
I am quite new to programming and I am just starting using java. My task was to write a program using quick sort, I managed to write it but it always gives me an index out of bounds. Could anyone take a look at my code and help me by identifying what I am doing wrong? Thanks
This is the code for the main class.
package quicksort;
public class Quicksort {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] x = {5,3,10,1,9,8,7,4,2,6,0};
quicksort_class q = new quicksort_class(x);
q.sort();
for(int i = 0; i < 11-1; i++)
{
System.out.println(x[i]);
}
}
}
This is the code for quicksort_class.
public class quicksort_class {
int[] array1 = new int[11];
public quicksort_class(int[] w)
{
array1 = w;
}
public void partitionstep(int leftlimit, int rightlimit)
{
int LPointer = leftlimit;
int RPointer = rightlimit;
Random random = new Random();
int midpoint = random.nextInt(11);
int checknumber = array1[midpoint];
while(LPointer < RPointer)
{
while(array1[LPointer] <= checknumber)
{
LPointer = LPointer + 1;
}
while(array1[RPointer] >= checknumber)
{
RPointer = RPointer --;
}
swap(LPointer, RPointer);
partitionstep(leftlimit, midpoint - 1);
partitionstep(midpoint + 1, rightlimit);
}
}
public void swap(int x, int y)
{
int temp = array1[x];
array1[x] = array1[y];
array1[y] = temp;
}
public void sort()
{
partitionstep(0, array1.length - 1);
}
}
Your midpoint value should be calculated based on your leftLimit and rightLimit. It should not be a random value based off of the fixed value 11.
I have been developing an implementation of the neighbourhood algorithm in Java for a physics project I am working on. I'm brand new to Java so I apologize for any idiocy that results.
I have been getting the error
''
incompatible types
found : void
required: java.util.List<VoronoiPoint>
'' on line 22 from the Java compiler in attempting to compile the program shown below. I cannot figure out why the variable ''thelist'' somehow turns into a void when I declared it to be of type List<VoronoiPoint>. If anybody can explain to me what is going on it would be much appreciated!
import java.lang.Double;
import java.util.*;
public class VoronoiTiling
{
public static void main(String args[])
{
Integer n = 10; //Number of dimensions of model parameter space
Integer ns = 20; //Number of points per iteration
Integer nr = 4; //Number of cells to populate
Integer iterations = 5; //Number of iterations
List<VoronoiPoint> thelist = VoronoiList.startlist(ns,n);
//System.out.println(thelist);
//System.out.println(thelist.get(1).misfit);
for (Integer i=0 ; i<thelist.size() ; i++)
{
thelist.get(i).setmisfit();
}
List<VoronoiPoint> orderedlist = Collections.sort(thelist);
Double distance = EuclidianDistance((thelist.get(1)).location,(thelist.get(2)).location);
System.out.println(distance);
}
public static Double EuclidianDistance(Double[] point1, Double[] point2)
{
Double distance=0.0;
for (int i = 0; i < point1.length; i++)
{
distance = distance + Math.pow((point1[i]-point2[i]),2);
}
return Math.sqrt(distance);
}
}
The other classes I used are here:
The VoronoiList class:
import java.util.*;
public class VoronoiList
{
public static List<VoronoiPoint> startlist(Integer ns, Integer n)
{
List<VoronoiPoint> thestartlist = new ArrayList<VoronoiPoint>();
for (int i = 0; i < ns; i++)
{
thestartlist.add(new VoronoiPoint(0.,n));
}
return thestartlist;
}
}
The VoronoiPoint class:
import java.util.Random;
public class VoronoiPoint implements Comparable<VoronoiPoint>
{
Double[] location;
private Random generator = new Random();
Double misfit = -1.;
//***************************************************************
public VoronoiPoint(Double misfit, Integer n)
{
location = new Double[n];
ParameterBoundaries boundaries = new ParameterBoundaries(n);
for(int i = 0; i < n; i++)
{
location[i] = boundaries.getboundaries(2*i)+2*generator.nextDouble();
}
}
//***************************************************************
//public Double[] getlocation()
//{
//return location;
//}
public void setlocationi(Integer i, Double j)
{
location[i] = j;
}
//***************************************************************
public void setmisfit()
{
Integer n = location.length;
Double tempmisfit = 0.0;
for(Integer i = 0; i < n; i++)
{
tempmisfit = tempmisfit + Math.pow((location[i]),2);
}
misfit = Math.sqrt(tempmisfit); // Temporarily just distance to centre
}
//public Double getmisfit()
//{
//return misfit;
//}
public int compareTo(VoronoiPoint b)
{
if (this.misfit<b.misfit) return -1;
else if (this.misfit==b.misfit) return 0;
return 1;
}
}
And the parameter boundaries class:
public class ParameterBoundaries
{
private Double[] boundaries; /*Set to 2n where n is dimensions of parameter space,
* it just makes it easier*/
public ParameterBoundaries(Integer n)
{
boundaries = new Double[2*n];
for(Integer i = 0; i<n; i++)
{
boundaries[2*i] = -1.0;
boundaries[2*i+1] = 1.0;
}
}
public Double getboundaries(Integer i)
{
return boundaries[i];
}
}
Collections.sort(..) sorts the original list. It doesn't return a new list. (Its return type is void)
Your code is wrong. Collections.sort() is an in-place sort function; it modifies the given list argument and returns nothing (void).