I'm new to java and I have a weighted union find algorithm. When I run this code in eclipse on a scrapbook page, it keeps evaluating forever.
java code
public class weightedUF {
private int[] id;
private int[] sz;
public weightedUF(int N) {
id = new int[N];
sz = new int[N];
for (int i = 0; i < N; i++) {
id[i] = i;
}
for (int i = 0; i < N; i++) {
sz[i] = 1;
}
}
private int root(int i) {
while (i != id[i]) {
i = id[i];
}
return i;
}
public boolean connected(int p, int q) {
return root(p) == root(q);
}
public void union(int p, int q) {
int i = root(p);
int j = root(q);
if (sz[i] < sz[j]) {
id[i] = j;
sz[j] += sz[i];
}
else {
id[j] = i;
sz[i] += sz[j];
}
id[i] = j;
}
}
scrapbook test code
weightedUF union = new weightedUF(10);
union.union(9, 2);
union.union(5, 2);
union.union(1, 8);
union.union(5, 7);
union.union(4, 3);
union.union(0, 7);
union.union(1, 3);
union.union(2, 4);
union.union(8, 6);
union
I think you should remove your last line :
id[i] = j;
it's corrupting your id array.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 days ago.
Improve this question
I'm trying to implement the A* algorithm in Java in order to solve the 15-Puzzle, but I get an infinite loop and I don't understand why.
I tried with the removal of the openList.clear(); statement, but in this way I get another problem: the tiles begin to do some erroneous movements.
Here is the code of the Board:
public class BoardPrototype implements Prototype, Cloneable {
public Box[][] board;
public int manhattanDistance = 0;
public int g_n = 0;
public final List<Integer> finalList = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0);
#Override
public Object clone() {
try {
BoardPrototype cloned = (BoardPrototype) super.clone();
cloned.board = new Box[board.length][board[0].length];
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
cloned.board[i][j] = new BoxBuilder()
.setX(board[i][j].getX())
.setY(board[i][j].getY())
.setValue(board[i][j].getValue())
.setG_n(board[i][j].getG_n())
.setInitialX(board[i][j].getInitialX())
.setInitialY(board[i][j].getInitialY())
.setManhattanDistance(board[i][j].getManhattanDistance())
.build();
}
}
return cloned;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
#Override
public boolean equals(Object o) {
if (o instanceof BoardPrototype that) {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
if (board[i][j].getValue() != that.board[i][j].getValue())
return false;
}
}
return true;
} else {
return false;
}
}
#Override
public int hashCode() {
int result = Arrays.hashCode(board[0]);
for (int i = 1; i < board.length; i++) {
result = 31 * result + Arrays.hashCode(board[i]);
}
return result;
}
public void setBoard(Box[][] board) {
this.board = board;
}
public void setManhattanDistance(int manhattanDistance) {
this.manhattanDistance = manhattanDistance;
}
public int getManhattanDistance() {
manhattanDistance = 0;
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
manhattanDistance += board[i][j].getManhattanDistance();
}
}
return manhattanDistance;
}
public void setG_n(int g_n) {
this.g_n = g_n;
}
public int getG_n() {
return this.g_n;
}
public BoardPrototype swap(int index1, int index2) {
BoardPrototype copy = (BoardPrototype) this.clone();
int row1 = index1 / 4;
int col1 = index1 % 4;
int row2 = index2 / 4;
int col2 = index2 % 4;
copy.board[row1][col1].setManhattanDistance(copy.board[row1][col1].getManhattan(index2, copy.board[row1][col1].getValue()));
copy.board[row2][col2].setManhattanDistance(copy.board[row2][col2].getManhattan(index1, copy.board[row2][col2].getValue()));
copy.board[row1][col1].setValue(copy.board[row2][col2].getValue());
copy.board[row2][col2].setValue(0);
copy.board[row1][col1].setInitialX(copy.board[row2][col2].getInitialX());
copy.board[row2][col2].setInitialX(copy.board[row1][col1].getInitialX());
copy.board[row1][col1].setInitialY(copy.board[row2][col2].getInitialY());
copy.board[row2][col2].setInitialY(copy.board[row1][col1].getInitialY());
copy.board[row1][col1].setG_n(copy.board[row2][col2].getG_n() + 1);
copy.board[row2][col2].setG_n(copy.board[row1][col1].getG_n() + 1);
copy.board[row1][col1].update();
copy.board[row2][col2].update();
return copy;
}
public List<BoardPrototype> neighbors(BoardPrototype board) {
ArrayList<BoardPrototype> neighbors = new ArrayList<>();
int blankIndex = board.getBlankIndex();
int row = blankIndex / 4;
int col = blankIndex % 4;
if (row > 0) {
BoardPrototype cloned = (BoardPrototype) board.clone();
cloned = cloned.swap(blankIndex, blankIndex - 4);
cloned.setManhattanDistance(cloned.getManhattanDistance());
neighbors.add(cloned);
}
if (col > 0) {
BoardPrototype cloned = (BoardPrototype) board.clone();
cloned = cloned.swap(blankIndex, blankIndex - 1);
cloned.setManhattanDistance(cloned.getManhattanDistance());
neighbors.add(cloned);
}
if (row < 3) {
BoardPrototype cloned = (BoardPrototype) board.clone();
cloned = cloned.swap(blankIndex, blankIndex + 4);
cloned.setManhattanDistance(cloned.getManhattanDistance());
neighbors.add(cloned);
}
if (col < 3) {
BoardPrototype cloned = (BoardPrototype) board.clone();
cloned = cloned.swap(blankIndex, blankIndex + 1);
cloned.setManhattanDistance(cloned.getManhattanDistance());
neighbors.add(cloned);
}
return neighbors;
}
public int getBlankIndex() {
int index = 0;
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(this.board[i][j].getValue() == 0) {
index = i * 4 + j;
}
}
}
return index;
}
public boolean isSolved() {
int count = 0;
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(board[i][j].getValue() == finalList.get(count)) {
count++;
if (count == 16) {
return true;
}
} else {
return false;
}
}
}
return false;
}
}
And this one is the code of the class that implements the A* algorithm:
public class Game15Solver {
private static Game15Solver game15Solver;
ManhattanComparator manhattanComparator = new ManhattanComparator();
private Game15Solver() {}
public static Game15Solver getInstance() {
if(game15Solver == null) {
game15Solver = new Game15Solver();
}
return game15Solver;
}
public List<BoardPrototype> AStar(BoardPrototype board) {
PriorityQueue<BoardPrototype> openList = new PriorityQueue<>(manhattanComparator);
List<BoardPrototype> closeList = new ArrayList<>();
openList.add(board);
while (!openList.isEmpty()) {
BoardPrototype current = openList.poll();
closeList.add(current);
openList.clear();
if (current.isSolved()) {
System.out.println("Solved");
} else {
for (BoardPrototype neighbor : current.neighbors(current)) {
if (!closeList.contains(neighbor)) {
if(!openList.contains(neighbor)) {
neighbor.setG_n(current.getG_n() + 1);
openList.add(neighbor);
} else {
var tmpList = (Arrays.asList(openList.toArray()));
int ind = tmpList.indexOf(neighbor);
BoardPrototype boardPrototype = (BoardPrototype) tmpList.get(ind);
if(neighbor.getG_n() + 1 < boardPrototype.getG_n()) {
openList.remove(neighbor);
neighbor.setG_n(current.getG_n() + 1);
openList.add(neighbor);
}
}
}
}
}
}
return closeList;
}
}
Do you know how can I solve this problem? Thank you.
The code still error, even though I have already fixed almost half the program
this initialized at main class:
Getting the below error:
Exception in thread "main"
java.lang.NullPointerException
at Tugas7.No3.seqSearch(No3.java:72)
at Tugas7.No3Main.main(No3Main.java:27)
what are you expecting to get out?
I excepting the code when run can search the number
package Tugas7;
public class No3 {
public int[] data;
public int jumData,min,max;
;
public int baris, kolom, posisiBar, posisiKol, posisi;
public void No3(int[] data) {
sort(data, 0, 8);
}
private void merge(int[] data, int left, int middle, int right) {
int[] temp = new int[data.length];
for (int i = left; i <= right; i++) {
temp[i] = data[i];
}
int a = left;
int b = middle + 1;
int c = left;
while (a <= middle && b <= right) {
if (temp[a] <= temp[b]) {
data[c] = temp[a];
a++;
} else {
data[c] = temp[b];
b++;
}
c++;
}
int s = middle - a;
for (int i = 0; i <= s; i++) {
data[c + i] = temp[a + i];
}
}
private void sort(int data[], int left, int right) {
if (left < right) {
int middle = (left + right) / 2;
sort(data, left, middle);
sort(data, middle + 1, right);
merge(data, left, middle, right);
}
}
public void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public int[] Searching(int[] Data, int jmlData) {
this.jumData = 10;
data = new int[jumData];
for (int i = 0; i < jumData; i++) {
data[i] = Data[i];
}
return data;
}
public int seqSearch(int cari) {
this.posisi = -1;
for (int j = 0; j < 11; j++) {
if (data[j] == cari) {
posisi = j;
break;
}
}
return posisi;
}
public void TampilData() {
for (int i = 0; i < 10; i++) {
System.out.print(data[i] + " ");
}
System.out.println();
}
public void searchMax(int[] data) {
min = data[0];
max = data[0];
for (int i = 0; i < 10; i++) {
if (data[i] < min) {
min = data[i];
} else if (data[i] > max) {
max = data[i];
}
}
}
}
What is the simplest way to make a union or an intersection of Sets in Java? I've seen some strange solutions to this simple problem (e.g. manually iterating the two sets).
The simplest one-line solution is this:
set1.addAll(set2); // Union
set1.retainAll(set2); // Intersection
The above solution is destructive, meaning that contents of the original set1 my change.
If you don't want to touch your existing sets, create a new set:
var result = new HashSet<>(set1); // In Java 10 and above
Set<Integer> result = new HashSet<>(set1); // In Java < 10
result.addAll(set2); // Union
result.retainAll(set2); // Intersection
While guava for sure is neater and pretty much standard, here's a non destructive way to do union and intersect using only standard Java
Set s1 = Set.of(1,2,3);
Set s2 = Set.of(3,4,5);
Set union = Stream.concat(s1.stream(),s2.stream()).collect(Collectors.toSet());
Set intersect = s1.stream().filter(s2::contains).collect(Collectors.toSet());
You can achieve this using Google's Guava library. The following explanation is given below with the help of an example:
// Set a
Set<String> a = new HashSet<String>();
a.add("x");
a.add("y");
a.add("z");
// Set b
Set<String> b = new HashSet<String>();
b.add("x");
b.add("p");
b.add("q");
Now, Calculating Intersection of two Set in Java:
Set<String> intersection = Sets.intersection(a, b);
System.out.printf("Intersection of two Set %s and %s in Java is %s %n",
a.toString(), b.toString(), intersection.toString());
Output: Intersection of two Set [z, y, x] and [q, p, x] in Java is [x]
Similarly, Calculating Union of two Set in Java:
Set<String> union = Sets.union(a, b);
System.out.printf("Union of two Set %s and %s in Java is %s %n",
a.toString(), b.toString(), union.toString());
Output: Union of two Set [z, y, x] and [q, p, x] in Java is [q, p, x, z, y]
You can read more about guava library at https://google.github.io/guava/releases/18.0/api/docs/
In order to add guava library to your project, You can see https://stackoverflow.com/a/4648947/8258942
import java.util.*;
public class sets {
public static void swap(int array[], int a, int b) { // Swap function for sorting
int temp = array[a];
array[a] = array[b];
array[b] = temp;
}
public static int[] sort(int array[]) { // sort function for binary search (Selection sort)
int minIndex;
int j;
for (int i = 0; i < array.length; i++) {
minIndex = i;
for (j = i + 1; j < array.length; j++) {
if (array[minIndex] > array[j])
minIndex = j;
}
swap(array, minIndex, i);
}
return array;
}
public static boolean search(int array[], int search) { // Binary search for intersection and difference
int l = array.length;
int mid = 0;
int lowerLimit = 0, upperLimit = l - 1;
while (lowerLimit <= upperLimit) {
mid = (lowerLimit + upperLimit) / 2;
if (array[mid] == search) {
return true;
} else if (array[mid] > search)
upperLimit = mid - 1;
else if (array[mid] < search)
lowerLimit = mid + 1;
}
return false;
}
public static int[] append(int array[], int add) { // To add elements
int newArray[] = new int[array.length + 1];
for (int i = 0; i < array.length; i++) {
newArray[i] = array[i];
}
newArray[array.length] = add;
newArray = sort(newArray);
return newArray;
}
public static int[] remove(int array[], int index) { // To remove duplicates
int anotherArray[] = new int[array.length - 1];
int k = 0;
if (array == null || index < 0 || index > array.length) {
return array;
}
for (int i = 0; i < array.length; i++) {
if (index == i) {
continue;
}
anotherArray[k++] = array[i];
}
return anotherArray;
}
public static void Union(int A[], int B[]) { // Union of a set
int union[] = new int[A.length + B.length];
for (int i = 0; i < A.length; i++) {
union[i] = A[i];
}
for (int j = A.length, i = 0; i < B.length || j < union.length; i++, j++) {
union[j] = B[i];
}
for (int i = 0; i < union.length; i++) {
for (int j = 0; j < union.length; j++) {
if (union[i] == union[j] && j != i) {
union = remove(union, j); // Removing duplicates
}
}
}
union = sort(union);
System.out.print("A U B = {"); // Printing
for (int i = 0; i < union.length; i++) {
if (i != union.length - 1)
System.out.print(union[i] + ", ");
else
System.out.print(union[i] + "}");
}
}
public static void Intersection(int A[], int B[]) {
int greater = (A.length > B.length) ? (A.length) : (B.length);
int intersect[] = new int[1];
int G[] = (A.length > B.length) ? A : B;
int L[] = (A.length < B.length) ? A : B;
for (int i = 0; i < greater; i++) {
if (search(L, G[i]) == true) { // Common elements
intersect = append(intersect, G[i]);
}
}
for (int i = 0; i < intersect.length; i++) {
for (int j = 0; j < intersect.length; j++) {
if (intersect[i] == intersect[j] && j != i) {
intersect = remove(intersect, j); // Removing duplicates
}
}
}
System.out.print("A ∩ B = {"); // Printing
for (int i = 1; i < intersect.length; i++) {
if (i != intersect.length - 1)
System.out.print(intersect[i] + ", ");
else
System.out.print(intersect[i] + "}");
}
}
public static void difference(int A[], int B[]) {
int diff[] = new int[1];
int G[] = (A.length > B.length) ? A : B;
int L[] = (A.length < B.length) ? A : B;
int greater = G.length;
for (int i = 0; i < greater; i++) {
if (search(L, G[i]) == false) {
diff = append(diff, G[i]); // Elements not in common
}
}
for (int i = 0; i < diff.length; i++) {
for (int j = 0; j < diff.length; j++) {
if (diff[i] == diff[j] && j != i) {
diff = remove(diff, j); // Removing duplicates
}
}
}
System.out.println("Where A is the larger set, and B is the smaller set.");
System.out.print("A - B = {"); // Printing
for (int i = 1; i < diff.length; i++) {
if (i != diff.length - 1)
System.out.print(diff[i] + ", ");
else
System.out.print(diff[i] + "}");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the operation");
String operation = sc.next().toLowerCase();
System.out.println("Enter the length of the first set.");
int l1 = sc.nextInt();
System.out.println("Enter the length of the second set.");
int l2 = sc.nextInt();
int A[] = new int[l1];
int B[] = new int[l2];
System.out.println("Enter the elements of the first set.");
System.out.print("A = ");
for (int i = 0; i < l1; i++) {
A[i] = sc.nextInt();
}
System.out.println("Enter the elements of the second set.");
System.out.print("B = ");
for (int i = 0; i < l2; i++) {
B[i] = sc.nextInt();
}
A = sort(A); // Sorting the sets before passing
B = sort(B);
sc.close();
switch (operation) {
case "union":
Union(A, B);
break;
case "intersection":
Intersection(A, B);
break;
case "difference":
difference(B, A);
break;
default:
System.out.println("Invalid Operation");
}
}
}
When I think of union and intersection, it is in the first loop an operation on sets, i.e. a map
Set<T> x Set<T> → Set<T>Not clear, why it would appear in Java design that shirtsleeved.
static <T> Set<T> union(Set<T> a, Set<T> b)
{
Set<T> res = new HashSet<T>(a);
res.addAll(b);
return res;
}
static <T> Set<T> intersection(Set<T> a, Set<T> b)
{
Set<T> res = new HashSet<T>(a);
res.retainAll(b);
return res;
}
I've been searching for an answer, but without any results. I know that this exception means that I'm trying to reach nonexistent array element, but I just can't see it.
It's excercise 104 from MOOC Helsinki, you can read it here
http://mooc.cs.helsinki.fi/programming-part1/material-2013/week-6?noredirect=1
I'm supposed to create sorting algorithm by creating five methods one after another. I've created first four, but things go south with the final one. I have no idea whether it's just matter of changing a single character, or the whole construction is flawed.
I would be grateful for help, feel free to comment on my code, but if it's possible do not overwrite the whole thing, I don't want solving it for me, just some hints and help.
import java.util.Arrays;
public class Main {
public static int smallest(int[] array) {
int result = array[0];
int position = 0;
for (int i = 0; i < (array.length); i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return result;
}
public static int indexOfTheSmallest(int[] array) {
int result = array[0];
int position = 0;
for (int i = 0; i < (array.length); i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return position;
}
public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
int result = array[index];
int position = 0;
for (int i = index; i < array.length; i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return position;
}
public static void swap(int[] array, int index1, int index2) {
int a = array[index1];
int b = array[index2];
array[index1] = b;
array[index2] = a;
}
public static void sort(int[] array) {
int temp;
for (int x = 0; x < array.length; x++) {
System.out.println(Arrays.toString(array));
temp = indexOfTheSmallestStartingFrom(array, x);
swap(array, array[x], temp);
}
}
public static void main(String[] args) {
int[] values = {8, 3, 7, 9, 1, 2, 4};
sort(values);
}
}
change swap(array, array[x], temp); to
swap(array, x, temp);
Try this out,
import java.util.Arrays;
public class Main {
public static int smallest(int[] array) {
int result = array[0];
int position = 0;
for (int i = 0; i < (array.length); i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return result;
}
public static int indexOfTheSmallest(int[] array) {
int result = array[0];
int position = 0;
for (int i = 0; i < (array.length); i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return position;
}
public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
int result = array[index];
int position = 0;
for (int i = index; i < array.length; i++) {
if (result > array[i]) {
result = array[i];
position = i;
}
}
return position;
}
public static void swap( int index1, int index2) {
int a = array[index1];
int b = array[index2];
array[index1] = b;
array[index2] = a;
}
public static void sort() {
int temp;
for (int x = 0; x < array.length; x++) {
System.out.println(Arrays.toString(array));
temp = indexOfTheSmallestStartingFrom(array, x);
swap( x, temp);
}
}
static int [] array= {8, 3, 7, 9, 1, 2, 4};
public static void main(String[] args) {
sort();
}
}
swap function was making changes but they weren't reflected because you were using pass-by-value.
I haven't touched the algorithm because the output is not as expected.
I'm trying to implement memoized version of recursive rod cutting algorithm. Here is my code (I implemented it from Cormen's pseudo code)
public class simpleMemoized {
//finds maximum of two given integers
public static int max(int a, int b) {
return (a > b) ? a : b;
}
public static int MemoizedCutRod(int price, int lenght) {
int[] r = new int[lenght + 1];
for (int i = 1; i <= lenght; i++) {
r[i] = 0;
}
return MemoizedCutRodAux(price, lenght, r);
}
public static int MemoizedCutRodAux(int price, int lenght, int[] r) {
int[] priceTable = new int[11];
priceTable[1] = 1;
priceTable[2] = 5;
priceTable[3] = 8;
priceTable[4] = 9;
priceTable[5] = 10;
priceTable[6] = 17;
priceTable[7] = 17;
priceTable[8] = 20;
priceTable[9] = 24;
priceTable[10] = 30;
if (r[lenght] >= 0) {
return r[lenght];
}
if (lenght == 0) {
return 0;
}
int q = 0;
for (int i = 1; i <= lenght; i++) {
q = max(q, priceTable[i] + MemoizedCutRodAux(price, lenght, r));
r[lenght] = q;
}
return q;
}
All outputs of this code are 0. But non memorized version of this code is working. What is the problem with it? Here is the working code:
public class Simple {
//finds maximum of two given integers
public static int max(int a, int b) {
return (a > b) ? a : b;
}
public static int cormenCutRod(int price, int lenght) {
int[] priceTable = new int[11];
priceTable[1] = 1;
priceTable[2] = 5;
priceTable[3] = 8;
priceTable[4] = 9;
priceTable[5] = 10;
priceTable[6] = 17;
priceTable[7] = 17;
priceTable[8] = 20;
priceTable[9] = 24;
priceTable[10] = 30;
if (lenght == 0) {
return 0;
}
int q = 0;
for (int i = 1; i <= lenght; i++) {
q = max(q, priceTable[i] + cormenCutRod(price, lenght - i));
}
return q;
}
This should work.
static int cutRodM(int lenght)
{
int[] priceTable = new int[11];
priceTable[1] = 1;
priceTable[2] = 5;
priceTable[3] = 8;
priceTable[4] = 9;
priceTable[5] = 10;
priceTable[6] = 17;
priceTable[7] = 17;
priceTable[8] = 20;
priceTable[9] = 24;
priceTable[10] = 30;
int[] mem= new int[lenght+1];
mem[0] = 0;
int i, j;
//filling the table bottom up
for (i = 1; i<=lenght; i++)
{
int q = 0;
for (j = 1; j <= i; j++)
q = max(q, priceTable[j] + mem[i-j]);
mem[i] = q;
}
return mem[lenght];
}
Ideone link: http://ideone.com/OWgrAZ