ronantakizawa/codereview-bench huggingface dataset:
Repository: TheAlgorithms/Java
File: src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java (Java)

Code before:
package com.thealgorithms.datastructures.graphs;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.stream.IntStream;

/*
 *  The Welsh-Powell algorithm is a graph coloring algorithm
 *  used for coloring a graph with the minimum number of colors.
 *  https://en.wikipedia.org/wiki/Graph_coloring
 */

public class WelshPowell {

    static class WPGraph {
        private int numVer; // Number of vertices in the graph
        private HashSet<Integer>[] adjLists; // Adjacency lists for the graph

        private WPGraph(int vertices) {
            numVer = vertices;
            adjLists = new HashSet[vertices];
            Arrays.setAll(adjLists, i -> new HashSet<>());
        }

        private void addEdge(int nodeA, int nodeB) {
            adjLists[nodeA].add(nodeB);
            adjLists[nodeB].add(nodeA);
        }

        HashSet<Integer> getAdjList(int vertex) {
            return adjLists[vertex];
        }

        int getNumVertices() {
            return numVer;
        }
    }


Review comment (refactor):
What do you think about making this class a _proper utility_?

```suggestion
public final class WelshPowell {
    private WelshPowell() {
    }
```

Code after:
package com.thealgorithms.datastructures.graphs;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.stream.IntStream;

/*
 *  The Welsh-Powell algorithm is a graph coloring algorithm
 *  used for coloring a graph with the minimum number of colors.
 *  https://en.wikipedia.org/wiki/Graph_coloring
 */

public final class WelshPowell {
    private static final int BLANK_COLOR = -1; // Representing uncolored state

    private WelshPowell() {
    }

    static class Graph {
        private HashSet<Integer>[] adjacencyLists;

        private Graph(int vertices) {
            if (vertices < 0) {
                throw new IllegalArgumentException("Number of vertices cannot be negative");
            }

            adjacencyLists = new HashSet[vertices];
            Arrays.setAll(adjacencyLists, i -> new HashSet<>());
        }

        private void addEdge(int nodeA, int nodeB) {
            validateVertex(nodeA);
            validateVertex(nodeB);
            if (nodeA == nodeB) {
                throw new IllegalArgumentException("Self-loops are not allowed");
            }
            adjacencyLists[nodeA].add(nodeB);
            adjacencyLists[nodeB].add(nodeA);
Repository: TheAlgorithms/Java
File: src/test/java/com/thealgorithms/datastructures/graphs/WelshPowellTest.java (Java)

Code before:
package com.thealgorithms.datastructures.graphs;

import static org.junit.jupiter.api.Assertions.*;

import com.thealgorithms.datastructures.graphs.WelshPowell.Graph;
import java.util.Arrays;
import org.junit.jupiter.api.Test;

class WelshPowellTest {

    @Test
    void testSimpleGraph() {
        final var graph = WelshPowell.makeGraph(4, new int[][] {{0, 1}, {1, 2}, {2, 3}});
        int[] colors = WelshPowell.findColoring(graph);
        assertTrue(isColoringValid(graph, colors));
        assertEquals(2, countDistinctColors(colors));
    }

    @Test
    void testDisconnectedGraph() {
        final var graph = WelshPowell.makeGraph(3, new int[][] {}); // No edges
        int[] colors = WelshPowell.findColoring(graph);
        assertTrue(isColoringValid(graph, colors));
        assertEquals(1, countDistinctColors(colors));
    }

    @Test
    void testCompleteGraph() {

Review comment (suggestion):
```suggestion
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
```

Code after:
package com.thealgorithms.datastructures.graphs;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.thealgorithms.datastructures.graphs.WelshPowell.Graph;
import java.util.Arrays;
import org.junit.jupiter.api.Test;

class WelshPowellTest {

    @Test
    void testSimpleGraph() {
        final var graph = WelshPowell.makeGraph(4, new int[][] {{0, 1}, {1, 2}, {2, 3}});
        int[] colors = WelshPowell.findColoring(graph);
        assertTrue(isColoringValid(graph, colors));
        assertEquals(2, countDistinctColors(colors));
    }

    @Test
    void testDisconnectedGraph() {
        final var graph = WelshPowell.makeGraph(3, new int[][] {}); // No edges
        int[] colors = WelshPowell.findColoring(graph);
        assertTrue(isColoringValid(graph, colors));
        assertEquals(1, countDistinctColors(colors));
    }
Repository: TheAlgorithms/Java
File: src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java (Java)

Code before:
    }

    /**
     * isEmpty helper method
     *
     * @return boolean true if the array contains no elements, false otherwise
     */
    public boolean isEmpty() {
        return this.size == 0;
    }

    public Stream<E> stream() {
        return StreamSupport.stream(spliterator(), false);
    }

    private void fastRemove(final Object[] elements, final int index) {
        final int newSize = this.size - 1;

        if (newSize > index) {
            System.arraycopy(elements, index + 1, elements, index, newSize - index);
        }

        elements[this.size = newSize] = null;
    }

    @SuppressWarnings("unchecked")
    private E getElement(final int index) {
        return (E) this.elements[index];
    }

    private int newCapacity(int capacity) {
        this.capacity = capacity;
        return this.capacity;
    }

    /**
     * returns a String representation of this object
     *
     * @return String a String representing the array
     */
    @Override
    public String toString() {
        return Arrays.toString(Arrays.stream(this.elements).filter(Objects::nonNull).toArray());
    }

    /**
     * Creates and returns a new Dynamic Array Iterator
     *
     * @return Iterator a Dynamic Array Iterator
     */
    @Override

Review comment (suggestion):
I would not introduce this suppression. Please revert the code to such stage that it is not needed and then (in a new PR) try to change it in such a way, that this will not be needed. Furthermore it seems that `DynamicArray` does not have any tests.

Code after:
    }

    /**
     * isEmpty helper method
     *
     * @return boolean true if the array contains no elements, false otherwise
     */
    public boolean isEmpty() {
        return this.size == 0;
    }

    public Stream<E> stream() {
        return StreamSupport.stream(spliterator(), false);
    }

    private void fastRemove(final Object[] elements, final int index) {
        final int newSize = this.size - 1;

        if (newSize > index) {
            System.arraycopy(elements, index + 1, elements, index, newSize - index);
        }

        elements[this.size = newSize] = null;
    }

    private E getElement(final int index) {
        return (E) this.elements[index];
    }

    private int newCapacity(int capacity) {
        this.capacity = capacity;
        return this.capacity;
    }

    /**
     * returns a String representation of this object
     *
     * @return String a String representing the array
     */
    @Override
    public String toString() {
        return Arrays.toString(Arrays.stream(this.elements).filter(Objects::nonNull).toArray());
    }

    /**
     * Creates and returns a new Dynamic Array Iterator
     *
     * @return Iterator a Dynamic Array Iterator
     */
    @Override
    public Iterator<E> iterator() {
Repository: TheAlgorithms/Java
File: src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java (Java)

Code before:
        if (pos > size || pos < 0) {
            // catching errors
            throw new IndexOutOfBoundsException("position cannot be greater than size or negative");
        }
        // we need to keep track of the element before the element we want to remove we
        // can see why bellow.
        Node<E> before = head;
        for (int i = 1; i <= pos; i++) {
            before = before.next;
        }
        Node<E> destroy = before.next;
        E saved = destroy.value;
        // assigning the next reference to the element following the element we
        // want to remove the last element will be assigned to the head.
        before.next = before.next.next;
        // scrubbing
        if (destroy == tail) {
            tail = before;
        }
        destroy = null;
        size--;
        return saved;
    }

    public static void main(String[] args) {
        CircleLinkedList<Integer> cl = new CircleLinkedList<Integer>();
        cl.append(12);
        System.out.println(cl);
        cl.append(23);
        System.out.println(cl);
        cl.append(34);
        System.out.println(cl);
        cl.append(56);
        System.out.println(cl);
        cl.remove(3);
        System.out.println(cl);
    }
}


Review comment (suggestion):
```suggestion
        CircleLinkedList<Integer> cl = new CircleLinkedList<>();
```

Code after:
        }
        // we need to keep track of the element before the element we want to remove we can see why
        // bellow.
        Node<E> before = head;
        for (int i = 1; i <= pos; i++) {
            before = before.next;
        }
        Node<E> destroy = before.next;
        E saved = destroy.value;
        // assigning the next reference to the element following the element we want to remove...
        // the last element will be assigned to the head.
        before.next = before.next.next;
        // scrubbing
        if (destroy == tail) {
            tail = before;
        }
        destroy = null;
        size--;
        return saved;
    }

    public static void main(String[] args) {
        CircleLinkedList<Integer> cl = new CircleLinkedList<>();
        cl.append(12);
        System.out.println(cl);
        cl.append(23);
        System.out.println(cl);
        cl.append(34);
        System.out.println(cl);
        cl.append(56);
        System.out.println(cl);
        cl.remove(3);
        System.out.println(cl);
    }
}
Repository: TheAlgorithms/Java
File: src/main/java/com/thealgorithms/misc/ThreeSumProblem.java (Java)

Code before:
                } else if (nums[start] + nums[end] + nums[i] < target) {
                    start += 1;
                } else {
                    end -= 1;
                }
            }
            i++;
        }
        Set<List<Integer>> set = new LinkedHashSet<List<Integer>>(arr);
        return new ArrayList<List<Integer>>(set);
    }

    public List<List<Integer>> Hashmap(int[] nums, int target) {
        Arrays.sort(nums);
        Set<List<Integer>> ts = new HashSet<List<Integer>>();
        HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();

        for (int i = 0; i < nums.length; i++) {
            hm.put(nums[i], i);
        }

        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                int t = target - nums[i] - nums[j];
                if (hm.containsKey(t) && hm.get(t) > j) {
                    List<Integer> temp = new ArrayList<Integer>();
                    temp.add(nums[i]);
                    temp.add(nums[j]);
                    temp.add(t);
                    ts.add(temp);
                }
            }
        }
        return new ArrayList<List<Integer>>(ts);
    }
}


Review comment (suggestion):
```suggestion
                    List<Integer> temp = new ArrayList<>();
```

Code after:
                } else if (nums[start] + nums[end] + nums[i] < target) {
                    start += 1;
                } else {
                    end -= 1;
                }
            }
            i++;
        }
        Set<List<Integer>> set = new LinkedHashSet<List<Integer>>(arr);
        return new ArrayList<List<Integer>>(set);
    }

    public List<List<Integer>> Hashmap(int[] nums, int target) {
        Arrays.sort(nums);
        Set<List<Integer>> ts = new HashSet<>();
        HashMap<Integer, Integer> hm = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            hm.put(nums[i], i);
        }

        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                int t = target - nums[i] - nums[j];
                if (hm.containsKey(t) && hm.get(t) > j) {
                    List<Integer> temp = new ArrayList<>();
                    temp.add(nums[i]);
                    temp.add(nums[j]);
                    temp.add(t);
                    ts.add(temp);
                }
            }
        }
        return new ArrayList<>(ts);
    }
}
Repository: TheAlgorithms/Java
File: src/main/java/com/thealgorithms/misc/ThreeSumProblem.java (Java)

Code before:
        Set<List<Integer>> set = new LinkedHashSet<List<Integer>>(arr);
        return new ArrayList<List<Integer>>(set);
    }

    public List<List<Integer>> Hashmap(int[] nums, int target) {
        Arrays.sort(nums);
        Set<List<Integer>> ts = new HashSet<List<Integer>>();
        HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();

        for (int i = 0; i < nums.length; i++) {
            hm.put(nums[i], i);
        }

        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                int t = target - nums[i] - nums[j];
                if (hm.containsKey(t) && hm.get(t) > j) {
                    List<Integer> temp = new ArrayList<Integer>();
                    temp.add(nums[i]);
                    temp.add(nums[j]);
                    temp.add(t);
                    ts.add(temp);
                }
            }
        }
        return new ArrayList<List<Integer>>(ts);
    }
}


Review comment (suggestion):
```suggestion
        return new ArrayList<>(ts);
```

Code after:
        Set<List<Integer>> set = new LinkedHashSet<List<Integer>>(arr);
        return new ArrayList<List<Integer>>(set);
    }

    public List<List<Integer>> Hashmap(int[] nums, int target) {
        Arrays.sort(nums);
        Set<List<Integer>> ts = new HashSet<>();
        HashMap<Integer, Integer> hm = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            hm.put(nums[i], i);
        }

        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                int t = target - nums[i] - nums[j];
                if (hm.containsKey(t) && hm.get(t) > j) {
                    List<Integer> temp = new ArrayList<>();
                    temp.add(nums[i]);
                    temp.add(nums[j]);
                    temp.add(t);
                    ts.add(temp);
                }
            }
        }
        return new ArrayList<>(ts);
    }
}
Repository: TheAlgorithms/Java
File: src/main/java/com/thealgorithms/searches/UnionFind.java (Java)

Code before:
            return i;
        }

        return p[i] = find(parent);
    }

    public void union(int x, int y) {
        int r0 = find(x);
        int r1 = find(y);

        if (r1 == r0) {
            return;
        }

        if (r[r0] > r[r1]) {
            p[r1] = r0;
        } else if (r[r1] > r[r0]) {
            p[r0] = r1;
        } else {
            p[r1] = r0;
            r[r0]++;
        }
    }

    public int count() {
        List<Integer> parents = new ArrayList<Integer>();
        for (int i = 0; i < p.length; i++) {
            if (!parents.contains(find(i))) {
                parents.add(find(i));
            }
        }
        return parents.size();
    }

    public String toString() {
        return "p " + Arrays.toString(p) + " r " + Arrays.toString(r) + "\n";
    }

    // Tests
    public static void main(String[] args) {
        UnionFind uf = new UnionFind(5);
        System.out.println("init /w 5 (should print 'p [0, 1, 2, 3, 4] r [0, 0, 0, 0, 0]'):");
        System.out.println(uf);

        uf.union(1, 2);
        System.out.println("union 1 2 (should print 'p [0, 1, 1, 3, 4] r [0, 1, 0, 0, 0]'):");
        System.out.println(uf);

        uf.union(3, 4);
        System.out.println("union 3 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):");
        System.out.println(uf);

Review comment (suggestion):
```suggestion
        List<Integer> parents = new ArrayList<>();
```

Code after:
            return i;
        }

        return p[i] = find(parent);
    }

    public void union(int x, int y) {
        int r0 = find(x);
        int r1 = find(y);

        if (r1 == r0) {
            return;
        }

        if (r[r0] > r[r1]) {
            p[r1] = r0;
        } else if (r[r1] > r[r0]) {
            p[r0] = r1;
        } else {
            p[r1] = r0;
            r[r0]++;
        }
    }

    public int count() {
        List<Integer> parents = new ArrayList<>();
        for (int i = 0; i < p.length; i++) {
            if (!parents.contains(find(i))) {
                parents.add(find(i));
            }
        }
        return parents.size();
    }

    public String toString() {
        return "p " + Arrays.toString(p) + " r " + Arrays.toString(r) + "\n";
    }

    // Tests
    public static void main(String[] args) {
        UnionFind uf = new UnionFind(5);
        System.out.println("init /w 5 (should print 'p [0, 1, 2, 3, 4] r [0, 0, 0, 0, 0]'):");
        System.out.println(uf);

        uf.union(1, 2);
        System.out.println("union 1 2 (should print 'p [0, 1, 1, 3, 4] r [0, 1, 0, 0, 0]'):");
        System.out.println(uf);

        uf.union(3, 4);
        System.out.println("union 3 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):");
        System.out.println(uf);
Repository: TheAlgorithms/Java
File: src/main/java/com/thealgorithms/backtracking/ParenthesesGenerator.java (Java)

Code before:
package com.thealgorithms.backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * This class generates all valid combinations of parentheses for a given number of pairs using backtracking.
 */
public class ParenthesesGenerator {
    /**
     * Generates all valid combinations of parentheses for a given number of pairs.
     *
     * @param n The number of pairs of parentheses.
     * @return A list of strings representing valid combinations of parentheses.
     * @throws IllegalArgumentException if n is less than 0.
     */
    public static List<String> generateParentheses(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("The number of pairs of parentheses cannot be nagative");
        }
        List<String> result = new ArrayList<>();
        generateParenthesesHelper(result, "", 0, 0, n);
        return result;
    }

    /**
     * Helper function for generating all valid combinations of parentheses recursively.
     *
     * @param result  The list to store valid combinations.
     * @param current The current combination being formed.
     * @param open    The number of open parentheses.
     * @param close   The number of closed parentheses.
     * @param n       The total number of pairs of parentheses.
     */

Review comment (refactor):
One can make this class a _proper utility_

```suggestion
public final class ParenthesesGenerator {
    private ParenthesesGenerator() {
    }
```

Going back to the `static`/non-static discussion: please have in mind that as soon as you mark something as `static` you lose the _object oriented magic_ (e.g. polymorphism). Even if the object of a given class does not hold any _state_ it  might make sense to still have it.

In case of this class - I would do it in the same way as it is done now.

Code after:
package com.thealgorithms.backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * This class generates all valid combinations of parentheses for a given number of pairs using backtracking.
 */
public final class ParenthesesGenerator {
    private ParenthesesGenerator() {
    }

    /**
     * Generates all valid combinations of parentheses for a given number of pairs.
     *
     * @param n The number of pairs of parentheses.
     * @return A list of strings representing valid combinations of parentheses.
     * @throws IllegalArgumentException if n is less than 0.
     */
    public static List<String> generateParentheses(final int n) {
        if (n < 0) {
            throw new IllegalArgumentException("The number of pairs of parentheses cannot be nagative");
        }
        List<String> result = new ArrayList<>();
        generateParenthesesHelper(result, "", 0, 0, n);
        return result;
    }

    /**
     * Helper function for generating all valid combinations of parentheses recursively.
     *
     * @param result  The list to store valid combinations.
     * @param current The current combination being formed.
     * @param open    The number of open parentheses.
Repository: TheAlgorithms/Java
File: src/test/java/com/thealgorithms/backtracking/ParenthesesGeneratorTest.java (Java)

Code before:
package com.thealgorithms.backtracking;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

public class ParenthesesGeneratorTest {
    @ParameterizedTest
    @MethodSource("tcStream")
    void numberTests(int input, List<String> expected) {
        assertEquals(expected, ParenthesesGenerator.generateParentheses(input));
    }

    @ParameterizedTest
    @MethodSource("negativeInputStream")
    void negativeInputTest(int input) {
        assertThrows(IllegalArgumentException.class, () -> ParenthesesGenerator.generateParentheses(input));
    }

    private static Stream<Arguments> tcStream() {
        return Stream.of(Arguments.of(0, List.of("")), Arguments.of(1, List.of("()")), Arguments.of(2, List.of("(())", "()()")), Arguments.of(3, List.of("((()))", "(()())", "(())()", "()(())", "()()()")),
            Arguments.of(4, List.of("(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()")));
    }

    private static Stream<Arguments> negativeInputStream() {
        return Stream.of(Arguments.of(-1), Arguments.of(-5), Arguments.of(-10));
    }
}


Review comment (suggestion):
```suggestion
    void throwsForNegativeInputTest(int input) {
```

Code after:
package com.thealgorithms.backtracking;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

public class ParenthesesGeneratorTest {
    @ParameterizedTest
    @MethodSource("regularInputStream")
    void regularInputTests(int input, List<String> expected) {
        assertEquals(expected, ParenthesesGenerator.generateParentheses(input));
    }

    @ParameterizedTest
    @MethodSource("negativeInputStream")
    void throwsForNegativeInputTests(int input) {
        assertThrows(IllegalArgumentException.class, () -> ParenthesesGenerator.generateParentheses(input));
    }

    private static Stream<Arguments> regularInputStream() {
        return Stream.of(Arguments.of(0, List.of("")), Arguments.of(1, List.of("()")), Arguments.of(2, List.of("(())", "()()")), Arguments.of(3, List.of("((()))", "(()())", "(())()", "()(())", "()()()")),
            Arguments.of(4, List.of("(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()")));
    }

    private static Stream<Arguments> negativeInputStream() {
        return Stream.of(Arguments.of(-1), Arguments.of(-5), Arguments.of(-10));
    }
}