Find all combinations of n numbers of a given set of numbers - java

i want to write a app to find all possible combinations of n numbers of a given set of numbers and return a hashset of them..
for example if a give set{1,5,7,9} and size of set 2 then i will take:
[1, 5] [1, 7] [1, 9] [5, 7] [5, 9]
i have the following code from this post but i can't modified it for a given size of set every time.
import java.util.ArrayList;
import java.util.Arrays;
class SumSet {
static void sum_up_recursive(ArrayList<Integer> numbers,ArrayList<Integer> partial) {
System.out.println("sum("+Arrays.toString(partial.toArray())+")=");
for(int i=0;i<numbers.size();i++)
{
ArrayList<Integer> remaining = new ArrayList<Integer>();
int n = numbers.get(i);
for (int j=i+1; j<numbers.size();j++)
remaining.add(numbers.get(j));
ArrayList<Integer> partial_rec = new ArrayList<Integer>(partial);
partial_rec.add(n);
sum_up_recursive(remaining,partial_rec);
}
}
static void sum_up(ArrayList<Integer> numbers) {
sum_up_recursive(numbers,new ArrayList<Integer>());
}
public static void main(String args[]) {
Integer[] numbers = {1,5,7,9};
sum_up(new ArrayList<Integer>(Arrays.asList(numbers)));
}
}

thank you all...
Also i found this solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
public class Comb {
static HashSet combine(Integer[] arr, int k, int startId, int[] branch, int numElem,HashSet arrSet)
{
if (numElem == k)
{
//System.out.println("k: "+k+(Arrays.toString(branch)));
ArrayList<Integer> mySet = new ArrayList<Integer>();
for(int i=0;i<branch.length;i++)
{
mySet.add(branch[i]);
}
arrSet.add(mySet);
return arrSet;
}
for (int i = startId; i < arr.length; ++i)
{
branch[numElem++]=arr[i];
combine(arr, k, ++startId, branch, numElem, arrSet);
--numElem;
}
return arrSet;
}
public static void main(String args[])
{
int k = 3;
Integer[] input ={1,5,7,9}; "ABCD".toCharArray();
int[] branch = new int[k];//{0,0};//new char[k];
HashSet arrSet=new HashSet();
arrSet=combine(input, k, 0, branch, 0, arrSet);
}
}

I changed recursive method from niiraj874u's answer to return a value. So now it gives list of hash sets as you wanted.
static List<Set<Integer>> sum_up_recursive(List<Integer> numbers,
Set<Integer> partial , int sizeOfset) {
List<Set<Integer>> result = new ArrayList<Set<Integer>>();
if(partial.size() == sizeOfset)
result.add(partial);
for (int i = 0; i < numbers.size(); i++) {
ArrayList<Integer> remaining = new ArrayList<Integer>();
int n = numbers.get(i);
for (int j = i + 1; j < numbers.size(); j++)
remaining.add(numbers.get(j));
Set<Integer> partial_rec = new HashSet<Integer>(partial);
partial_rec.add(n);
result.addAll(sum_up_recursive(remaining, partial_rec, sizeOfset));
}
return result;
}
public static void main(String args[]) {
Integer[] numbers = { 1, 5, 7, 9 };
int size = 2;
List<Set<Integer>> allCombinations = sum_up_recursive(Arrays.asList(numbers), new HashSet<Integer>(), size);
for (Set<Integer> set : allCombinations) {
for (Integer num : set)
System.out.print(num + " ");
System.out.println();
}
}

package com.app.atb;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class Challenge {
public static void main(String[] args) {
Set<Integer> myset = new HashSet<Integer>();
myset.add(1);
myset.add(5);
myset.add(7);
myset.add(9);
List<Set<Integer>> achieved = solveChallenge(myset);
System.out.println(achieved);
}
public static List<Set<Integer>> solveChallenge(Set<Integer> myset) {
int n = myset.size();
Integer[] myInts = new Integer[n];
Iterator<Integer> iterator = myset.iterator();
int index = 0;
while (iterator.hasNext()) {
myInts[index] = iterator.next();
++index;
}
List<Set<Integer>> myList = new ArrayList<Set<Integer>>();
Set<Integer> subSet;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (j != i) {
subSet = new HashSet<Integer>();
subSet.add(myInts[i]);
subSet.add(myInts[j]);
myList.add(subSet);
}
}
}
return myList;
}
}

We can add one more parameter sizeOfset in SumSet.sum_up_recursive(ArrayList<Integer>, ArrayList<Integer>, int) method like below. please run it tell me Does it give the output what you want ?
import java.util.ArrayList;
import java.util.Arrays;
public class SumSet {
static void sum_up_recursive(ArrayList<Integer> numbers,
ArrayList<Integer> partial , int sizeOfset) {
if(partial.size() == sizeOfset)
{
System.out.println("sum(" + Arrays.toString(partial.toArray()) + ")=");
}
for (int i = 0; i < numbers.size(); i++) {
ArrayList<Integer> remaining = new ArrayList<Integer>();
int n = numbers.get(i);
for (int j = i + 1; j < numbers.size(); j++)
remaining.add(numbers.get(j));
ArrayList<Integer> partial_rec = new ArrayList<Integer>(partial);
partial_rec.add(n);
sum_up_recursive(remaining, partial_rec, sizeOfset);
}
}
static void sum_up(ArrayList<Integer> numbers) {
sum_up_recursive(numbers, new ArrayList<Integer>(), 2);
}
public static void main(String args[]) {
Integer[] numbers = { 1, 5, 7, 9 };
sum_up(new ArrayList<Integer>(Arrays.asList(numbers)));
}
}

Related

Print all subsets of an array

I'm trying to print all the subsets of an array. For example:
Input: nums = [1,2]
Output:
[[1], [2], [1,2], []]
I've written a recursive approach, given that all such solutions start with a condition and the program calls itself for a sub-array. But I get a ConcurrentModificationException at for(ArrayList<Integer>subset: subsets2).
How to fix the issues and convert it to a working solution?
UPDATE: I don't need a working solution. I need to fix my own code. Please work on my own code below:
import java.util.ArrayList;
import java.util.List;
public class TestPractice {
public static void main(String[] args){
int[] x = {1,2};
System.out.println(subsets(x));
}
public static List<ArrayList<Integer>> subsets(int[] nums) {
ArrayList<ArrayList<Integer>> subsets = new ArrayList<ArrayList<Integer>>();
if (nums.length ==1){
ArrayList<Integer> subset1 = new ArrayList<Integer>();
ArrayList<Integer> subset2 = new ArrayList<Integer>();
subset2.add(nums[0]);
subsets.add(subset1);
subsets.add(subset2);
return subsets;
}
int[] nums_1 = new int[nums.length-1];
for(int i = 0; i< nums.length-1; i++) {
nums_1[i]=nums[i];
}
List<ArrayList<Integer>> subsets2= subsets(nums_1);
//now add nums[n] to all subsets of nums[0:n-1]
for(ArrayList<Integer>subset: subsets2) {
ArrayList<Integer> subset1 = new ArrayList<Integer>();
subset1.add(nums[nums.length-1]);
subset1.addAll(subset);
subsets2.add(subset1);
}
return subsets2;
}
}
Don't add elements to a List when you're iterating over it. Your code can be greatly simplified by only choosing to either take or not take the current element each time. Demo
public static Set<List<Integer>> subsets(Set<List<Integer>> result, ArrayList<Integer> curr, int[] nums, int idx) {
result.add((List<Integer>)curr.clone());
if(idx < nums.length){
subsets(result, curr, nums, idx + 1);
final ArrayList<Integer> next = (ArrayList<Integer>) curr.clone();
next.add(nums[idx]);
subsets(result, next, nums, idx + 1);
}
return result;
}
public static void main(String[] args){
int[] x = {1,2};
System.out.println(subsets(new HashSet<>(), new ArrayList<>(), x, 0));
}
You can also use bitmasking. Demo
public static Set<List<Integer>> subsets(int[] nums) {
final Set<List<Integer>> result = new HashSet<>();
for(int i = 0; i < 1 << nums.length; i++){
final List<Integer> curr = new ArrayList<>();
for(int j = 0; j < nums.length; j++){
if(((i>>j)&1)==1) curr.add(nums[j]);
}
result.add(curr);
}
return result;
}
public static void main(String[] args){
int[] x = {1,2,};
System.out.println(subsets(x));
}
concurrentmodificationexception occurs when you are looping and updating the same list , so create a new list and update that list inside the loop instead of subsets2.add(subset1).
Below I have create a new list result and updating result list inside loop instead of subset2
import java.util.ArrayList;
import java.util.List;
public class TestPractice {
public static void main(String[] args){
int[] x = {1,2};
System.out.println(subsets(x));
}
public static List<ArrayList<Integer>> subsets(int[] nums) {
ArrayList<ArrayList<Integer>> subsets = new ArrayList<ArrayList<Integer>>();
if (nums.length ==1){
ArrayList<Integer> subset1 = new ArrayList<Integer>();
ArrayList<Integer> subset2 = new ArrayList<Integer>();
subset2.add(nums[0]);
subsets.add(subset1);
subsets.add(subset2);
return subsets;
}
int[] nums_1 = new int[nums.length-1];
for(int i = 0; i< nums.length-1; i++) {
nums_1[i]=nums[i];
}
List<ArrayList<Integer>> subsets2= subsets(nums_1);
List<ArrayList<Integer>> result= subsets(nums_1);
//now add nums[n] to all subsets of nums[0:n-1]
for(ArrayList<Integer>subset: subsets2) {
ArrayList<Integer> subset1 = new ArrayList<Integer>();
subset1.add(nums[nums.length-1]);
subset1.addAll(subset);
result.add(subset1);
}
return result;
}
}
It can be solved using both, Iterative and Recursive Approach
For this problem using LinkedList is faster as compared to ArrayList
Also, you don't need to handle the case when nums.length == 1
Iterative Approach
import java.util.LinkedList;
import java.util.List;
public class TestPractice {
public static void main(String[] args) {
int[] x = { 1, 2 };
System.out.println(subsets(x));
}
public static List<LinkedList<Integer>> subsets(int[] nums) {
LinkedList<LinkedList<Integer>> subsets = new LinkedList<LinkedList<Integer>>();
subsets.add(new LinkedList<Integer>());
for(int i = 0; i < nums.length; i++) {
LinkedList<LinkedList<Integer>> temp = new LinkedList<LinkedList<Integer>>();
for(LinkedList<Integer> l1: subsets) {
LinkedList<Integer> l2 = new LinkedList<Integer>(l1);
l2.add(nums[i]);
temp.add(l2);
}
subsets.addAll(temp);
}
return subsets;
}
}
Recursive Approach
import java.util.LinkedList;
import java.util.List;
public class TestPractice {
public static void main(String[] args) {
int[] x = { 1, 2 };
System.out.println(subsets(x));
}
public static List<List<Integer>> subsets(int n[]) {
List<List<Integer>> subsets = new LinkedList<List<Integer>>();
helper(n, 0, subsets, new LinkedList<Integer>());
return subsets;
}
public static void helper(int[] n, int i, List<List<Integer>> subsets, LinkedList<Integer> subset1) {
if(i == n.length) {
subsets.add(subset1);
return;
}
helper(n, i + 1, subsets, subset1);
LinkedList<Integer> subset2 = new LinkedList<Integer>(subset1);
subset2.add(n[i]);
helper(n, i + 1, subsets, subset2);
}
}

Counting Sort implementation

Hello I am having difficulty implementing a counting sort method in java. I believe the problem comes from the last two loops I have in the method. I am getting an ArrayIndexOutOfBounds exception : 8. I believe this comes from my second to last for loop when at index 5 the value is 8 but I am not sure how to resolve this. Any help is appreciated. Thank you!
In my code k is the highest value in the input array.
Code:
public static void main(String[] args) {
int [] arrayOne = {0,1,1,3,4,5,3,0};
int [] output = Arrays.copyOf(arrayOne, arrayOne.length);
System.out.println(Arrays.toString(arrayOne));
countingSort(arrayOne, output, 5);
System.out.println(Arrays.toString(output));
}
public static void countingSort(int[] input, int[] output , int k){
int [] temp = Arrays.copyOf(input, k+1);
for (int i = 0; i <= k; i++){
temp[i] = 0;
}
for (int j = 0; j <= input.length - 1; j++){
temp[input[j]] = temp[input[j]] + 1;
}
for (int i = 1; i <= k; i++){
temp[i] = temp[i] + temp[i-1];
}
for (int j = input.length; j >= 1; j--){
output[temp[input[j]]] = input[j];
temp[input[j]] = temp[input[j]] - 1;
}
}
The problem is in the first loop because the array temp lenght is 6 and you are doing 7 interations in there.
So at the end of the for it is trying to do temp[6]=0 and the last position of your array is temp[5].
To fix this change your first loop to:
for (int i = 0; i < k; i++){
In the last loop you will get the same exception cause input[8] doesn't exist.
import java.util.Arrays;
public class CountingSort {
public static void main(String[] args) {
int[] input = {0,1,1,3,4,5,3,0};
int[] output = new int[input.length];
int k = 5; // k is the largest number in the input array
System.out.println("before sorting:");
System.out.println(Arrays.toString(input));
output = countingSort(input, output, k);
System.out.println("after sorting:");
System.out.println(Arrays.toString(output));
}
public static int[] countingSort(int[] input, int[] output, int k) {
int counter[] = new int[k + 1];
for (int i : input) { counter[i]++; }
int ndx = 0;
for (int i = 0; i < counter.length; i++) {
while (0 < counter[i]) {
output[ndx++] = i;
counter[i]--;
}
}
return output;
}
}
Above code is adapted from: http://www.java67.com/2017/06/counting-sort-in-java-example.html
this may help but try using the Arraya.sort() method.
e.g:
//A Java program to sort an array of integers in ascending order.
// A sample Java program to sort an array of integers
// using Arrays.sort(). It by default sorts in
// ascending order
import java.util.Arrays;
public class SortExample
{
public static void main(String[] args)
{
// Our arr contains 8 elements
int[] arr = {13, 7, 6, 45, 21, 9, 101, 102};
Arrays.sort(arr);
System.out.printf("Modified arr[] : %s",
Arrays.toString(arr));
}
}
example is a snippet from https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/
As per algorithm following implementation, I have prepared for the count sort technique
public static int[] countSort(int elements[]) {
int[] sorted = new int[elements.length+1];
int[] range = new int[getMax(elements)+1];
for(int i=0;i<range.length;i++) {
range[i] = getCount(i, elements);
try {
range[i] = range[i]+range[i-1];
}catch(ArrayIndexOutOfBoundsException ae) {
continue;
}
}
for(int i=0;i<elements.length;i++) {
sorted[range[elements[i]]] = elements[i];
range[elements[i]] = range[elements[i]]-1;
}
return sorted;
}
public static int getCount(int value,int[] elements) {
int count = 0;
for(int element:elements) {
if(element==value) count++;
}
return count;
}
public static int getMax(int elements[]) {
int max = elements[0];
for(int i=0;i<elements.length;i++) {
if(max<elements[i]) {
max = elements[i];
}
}
return max;
}
Please review and let me know if any feedback and it is more helpful.
Note :
Non-negative no won't support in the above implementation.
don't use 0th index of the sorted array.

Arraylist Insertion-Sort

How do you sort an arraylist using insertion? Here is my arraylist it is filled with random Integers:
ArrayList<Integer> oh = new ArrayList<Integer>();
Random random = new Random();
for (int i = 0; i < 100; i++)
{
oh.add(random.nextInt());
}
Try this can help you to solve problem, sorting Arraylist with insertion sort.
public static void main(String args[]) {
ArrayList<Integer> oh = new ArrayList<Integer>();
Random random = new Random();
for (int i = 0; i < 100; i++) {
oh.add(random.nextInt());
}
int[] elementlist = new int[oh.size()];
Iterator<Integer> iter = oh.iterator();
for (int j = 0; iter.hasNext(); j++) {
elementlist[j] = iter.next();
}
int[] list = insertionSort(elementlist);
for (Integer in : list) {
System.out.println(in);
}
}
public static int[] insertionSort(int[] list) {
for (int i = 1; i < list.length; i++) {
int next = list[i];
// find the insertion location while moving all larger element up
int j = i;
while (j > 0 && list[j - 1] > next) {
list[j] = list[j - 1];
j--;
}
// insert the element
list[j] = next;
}
return list;
}
For more info go in link
import java.util.ArrayList;
public class InsertionSort {
private static ArrayList<Integer> inputArray = new ArrayList<Integer>();
public static ArrayList<Integer> getInputArray() {
return inputArray;
}
public InsertionSort(ArrayList<Integer> inputArray){
InsertionSort.inputArray = inputArray;
}
public void sortGivenArray(){
for(int i=1;i<inputArray.size();i++){
int key = inputArray.get(i);
for(int j= i-1;j>=0;j--){
if(key<inputArray.get(j)){
inputArray.set(j+1,inputArray.get(j));
if(j==0){
inputArray.set(0, key);
}
}else{
inputArray.set(j+1,key);
break;
}
}
}
}
}
import java.util.ArrayList;
import daa.InsertionSort;
public class MainPractise implements Cloneable {
public static void main(String[] args) {
ArrayList<Integer> unsortedArray = new ArrayList<Integer>();
unsortedArray.add(8);
unsortedArray.add(7);
unsortedArray.add(6);
unsortedArray.add(5);
unsortedArray.add(4);
unsortedArray.add(0);
unsortedArray.add(2);
InsertionSort is = new InsertionSort(unsortedArray);
System.out.println("---------Initial Unsorted Array---------");
for(int i:InsertionSort.getInputArray()){
System.out.print(i+" ");
}
is.sortGivenArray();
System.out.println("\n------------Sorted Array------------");
for(int i:InsertionSort.getInputArray()){
System.out.print(i+" ");
}
}
}

How to detect repeated values in array of integer and create a new one with them in java?

everybody, I would be very thankful if You could help me in this question. The point is I have initial array "a" with bunch of numbers, some of them can repeat many times, some of them - once. The task is to create a new array "b" which consists of repeated numbers. If any number from array "a" repeats more than once - in array "b" it must be reflected only once. The sequence of elements in a new array shoulb be the same as in the initial.
For instance:
*initial array "a": 2 3 3 4 5 6 9 2 7 3 3
new array "b": 2 3*
I have decided to generate array "a" randomly every time, it's without any difficulties, but as regards defining repretitions have some problems. The only thing I have done is found all repeated numbers.And the result I have right now is
*initial array "a": 2 3 3 4 5 6 9 2 7 3 3
new array "b": 2 3 3 3*
My code:
import java.util.*;
public class ProcessingTool {
public static int[] arrayCreatingMethod(){
Random rand = new Random();
int myArrayDim = rand.nextInt(50);
int [] myArray = new int [myArrayDim];
for (int i=0; i<myArray.length;i++){
myArray[i] = (int)(Math.random()*(100));
}
return myArray;
}
public static int[] newArrayCreatingMethod(int[] a) {
int[] d = new int [a.length];
int k = 0;
int repetitions = 0;
for (int i = 0; i<a.length;i++){
int j = i;
int current = a[i];
while (j<a.length-1) {
if (current == a[j+1]) {
d[k] = current;
k++;
repetitions++;
break;
}
else {
k=k-1+1;
}
j++;
}
}
System.out.print("\n"+repetitions+"\n");
System.out.println("\nArray d: ");
for (int ww = 0; ww<d.length; ww++){
System.out.print(d[ww]+" ");
}
Using the proper classes simplifies this:
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
import org.junit.Assert;
public class Reducing {
public int[] reduce(int[] input) {
Set<Integer> vals = new LinkedHashSet<Integer>();
Set<Integer> recurrences = new LinkedHashSet<Integer>();
for (Integer i : input) {
if (vals.contains(i)) {
recurrences.add(i);
}
vals.add(i);
}
vals.retainAll(recurrences);
int index = 0;
Integer[] recurs = new Integer[vals.size()];
for (Integer i : vals) {
recurs[index++] = i;
}
return recurs;
}
#org.junit.Test
public void test() {
Integer[] input = {2, 3, 3, 4, 5, 6, 9, 2, 7, 3, 3};
System.out.println(Arrays.toString(reduce(input)));
}
}
public static int[] findRecurringNumbers(int[] array){
Map<Integer, Boolean> map = new HashMap<>();
for(Integer i : array){
Boolean recurred = map.get(i);
//if current number is unknown ==> recurred = null
//if current number occurred once ==> recurred = false
//if current number occurred more than once ==> recurred = true
map.put(i, recurred != null);
}
// as result, filter all entries' keys, where the corresponding value is TRUE
return map.entrySet().stream()
.filter(entry->entry.getValue())
.mapToInt(entry->entry.getKey()).toArray();
}
The above solution is tested with the following Junit test case:
#Test
public void testFind(){
int[] a = {2,3,5,3,2,3};
int[] expectedResult = {2,3};
int[] recurrence = findRecurringNumbers(a);
System.out.println("Recurrence: " + Arrays.toString(recurrence));
assertTrue(Arrays.equals(expectedResult, recurrence));
}
The console states:
Recurrence: [2, 3]
Here's a quick solution. It navigates through every element in array a to check to see if it occurs more than once, and if it does, it adds it to a HashSet.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class IntCount {
int [] a = new int [] {2,3,3,4,5,6,9,2,7,3,3};
public IntCount()
{
Set<Integer> b = new HashSet<Integer>();
for (int i : a)
{
if (containsTwice(i))
b.add(i);
}
System.out.println(Arrays.toString(b.toArray()));
}
boolean containsTwice(int i)
{
int count = 0;
for (int j : a)
{
if (j == i)
count++;
}
return (count > 1);
}
public static void main(String [] args)
{
new IntCount();
}
}
Output: [2, 3]
public static void main(String[] args) {
// TODO code application logic here
int[] a = {1,2,3,4,2,2,3,3,1,2};
int[] b = new int[a.length];
int bcount = 0;
for(int i=0; i<a.length; i++){
for(int j=i; j<a.length;j++){
if(a[i] == a[j] && i!=j){
boolean flag = true;
for(int q=0; q<bcount && flag; q++){
if(a[i] == b[q]){
flag = false;
}
}
if(flag){
b[bcount] = a[i];
bcount++;
}
}
}
}
//display
for(int i=0; i<bcount; i++){
System.out.print(b[i]+" ");
}
}
I think your problem is printing out the number that you already printed out. So, just include a loop to test it.
I hope it'd be helpful to you.

MergeSort Implementation IndexOutOfBounds Java

import java.util.ArrayList;
import java.util.Random;
public class Merge {
private static ArrayList<Integer> newArrayList;
public static ArrayList<Integer> generateArray(int n){
newArrayList = new ArrayList<Integer>(n);
Random rand = new Random();
for (int i = 0; i<n; i++){
newArrayList.add(rand.nextInt(n + 1));
}
return newArrayList;
}
public static ArrayList<Integer> mergeSort(ArrayList<Integer> x){
if (x.size()>1){
ArrayList<Integer> ArrayList1 = new ArrayList<Integer>(x.size()/2);
ArrayList<Integer> ArrayList2 = new ArrayList<Integer>(x.size()-(x.size()/2));
for (int i = 0; i<newArrayList.size()/2; i++){
ArrayList1.set(i, newArrayList.get(i));
}
for (int i = (newArrayList.size()/2); i<((newArrayList.size()/2)+(newArrayList.size()-newArrayList.size()/2)); i++){
ArrayList2.set(i-(newArrayList.size()/2), newArrayList.get(i));
}
//ArrayList1 = mergeSort(ArrayList1);
//ArrayList2 = mergeSort(ArrayList2);
int j = 0;
int k = 0;
int a = 0;
while(ArrayList1.size() != j && ArrayList2.size() != k){
if (ArrayList1.get(j) < ArrayList2.get(k)){
x.set(a, ArrayList1.get(j));
a++;
j++;
} else {
x.set(a, ArrayList2.get(k));
a++;
k++;
}
}
while (ArrayList1.size()!=j){
x.set(a, ArrayList1.get(j));
a++;
j++;
}
while (ArrayList2.size()!=k){
x.set(a, ArrayList2.get(k));
a++;
k++;
}
}
return x;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> new1;
//ArrayList<Integer> new2;
//ArrayList<Integer> new3;
new1 = generateArray(10);
//new2 = generateArray(100);
//new3 = generateArray(1000);
System.out.println(new1);
mergeSort(new1);
System.out.println(new1);
}
}
I am attempting to implement a mergeSort method but I keep getting the following error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.set(ArrayList.java:337)
at Merge.mergeSort(Merge.java:23)
at Merge.main(Merge.java:73)
Any ideas?
You are attempting to set a position that doesn't exist yet in your ArrayList called ArrayList1. You've set the initial capacity to x.size() / 2, but there's nothing in it yet.
It looks like you are attempting to set each position, starting with position 0, so just add the elements instead. Replace
for (int i = 0; i<newArrayList.size()/2; i++){
ArrayList1.set(i, newArrayList.get(i));
}
with
for (int i = 0; i<newArrayList.size()/2; i++){
ArrayList1.add(newArrayList.get(i));
}
And you'll need to make similar changes to the for loop after that, which populates ArrayList2.

Categories