Can't seem to fix my 'java.lang.ArrayIndexOutOfBoundsException' error - java

I'm unsure if the problem in my program is simply in where I declared the arrays, or if I'm stuffing one of them with more than they can take.
Here is my code:
import java.util.Scanner;
import java.util.Arrays;
public class EliminateDuplicates {
public static void main(String[] args) {
int[] numberList = new int[10];
System.out.println("Please enter ten integers.");
Scanner input = new Scanner(System.in);
for (int i = 0; i < numberList.length; i++) {
numberList[i] = input.nextInt();
}
int[] newNumberList = new int[10];
newNumberList = eliminateDuplicates(numberList);
System.out.println("The discrete numbers are: ");
for (int i = 0; i < newNumberList.length; i++) {
System.out.println(newNumberList[i] + ' ');
}
}
public static int[] eliminateDuplicates(int[] numberList) {
int[] noDuplicateList = new int[numberList.length];
int size = 0;
java.util.Arrays.sort(numberList);
for (int i = 0; i < numberList.length; i++) {
if (numberList[i] != numberList[i+1]) {
noDuplicateList[i] = numberList[i];
size++;
}
}
return noDuplicateList;
}
}
This is the output + the error message I get:
Please enter ten integers.
9
8
7
3
3
4
1
2
8
6
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at EliminateDuplicates.eliminateDuplicates(EliminateDuplicates.java:51)
at EliminateDuplicates.main(EliminateDuplicates.java:28)

Your problem is here :
for (int i = 0; i < numberList.length - 1; i++) {
if (numberList[i] != numberList[i+1]) {
When i reaches numberList.length-1, i+1 is out of the array bounds.
You should change the range of the loop. You shold also use the size index when assigning to the noDuplicateList list, otherwise you will have gaps in that list.
for (int i = 0; i < numberList.length - 1; i++) {
if (numberList[i] != numberList[i+1]) {
noDuplicateList[size] = numberList[i];
size++;
}
}
You would still have a minor problem. Since your eliminateDuplicates methods returns an array of the same size as the input, if there were duplicates, the output array would have unused indices in its end (that will contain zeroes). If you wish to avoid that, you can add all the items of the input array to a HashSet, find the size() of that set, and create an array of that size for the output. Using a Set will also simplify your code, since the Set would eliminate the duplicates for you, and you don't have to sort the input array.
public static int[] eliminateDuplicates(int[] numberList) {
Set<Integer> noDups = new HashSet<Integer>();
for (int num : numberList)
noDups.add(num);
int[] noDuplicateList = new int[noDups.size()];
Iterator<Integer> iter = noDups.iterator();
for (int i=0; i<noDuplicateList.length && iter.hasNext();i++)
noDuplicateList[i]=iter.next();
return noDuplicateList;
}

Your problem is here, eliminateDuplicates:
if (numberList[i] != numberList[i+1]) {// i+1, for the last elements raise the exception

if (numberList[i] != numberList[i+1])
when i=9 this would look for index 10 which is out of bound.

the problem is this line:
if (numberList[i] != numberList[i+1]) {
If i is equals numberList.length the second condition is out of bounds.
So you have to change:
for (int i = 0; i < numberList.length; i++) {
TO:
for (int i = 0; i < numberList.length-1; i++) {

Related

Splitting an array at multiple points using an index point

I have come across many examples to split the given array or array list into two arrays or multiple arrays using an index point. I tried them and they are working perfectly. My question is, is it possible to split the array into multiple arrays of varying chunk size given the index point?
For example:
array[] = {10,1,2,3,10,4,5,10,6,7,10,8,10};
index_value = 10;
Then the output should be four arrays such as:
arr1[] = {1,2,3}
arr2[] = {4,5}
arr3[] = {6,7}
arr4[] = {8}
I was able to split them and display the results when the given array is static with no changes. But implementing the same for an array with random numbers and random size was hard. I need to store the split values in many sub arrays and not just printing the values.
For this solution, the index_value does not have to be at the start or end of the array:
int[] arr = new int[]{10,10,1,10,1,2,3,10,4,5,10,6,7,10,8,10,9,8,7,6,5,4,3,10,1,2,3,4,5,6,7,10,5,4,10,10};
int index_value = 10;
/** walk through the array and create the arraylist of arraylists */
ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> currAl = null;
for (int i=0; i < arr.length; i++) {
if (arr[i] == index_value) {
if (currAl != null && currAl.size() > 0)
al.add(currAl);
currAl = new ArrayList<Integer>();
} else {
if (currAl == null)
currAl = new ArrayList<Integer>();
currAl.add(arr[i]);
}
}
if (arr[arr.length-1]!= index_value && currAl.size() > 0) {
al.add(currAl);
}
/** print out the arraylist of arraylists */
for (int i=0; i < al.size(); i++) {
currAl = al.get(i);
for (int j=0; j < currAl.size(); j++) {
System.out.print(currAl.get(j) + " ");
}
System.out.println();
}
You can build your arrays by using the ArrayList class to fill in your values
array[] = {10,1,2,3,10,4,5,10,6,7,10,8,10};
index_value = 10;
ArrayList<ArrayList<int>> allLists = new ArrayList<ArrayList<int>>();
ArrayList<int> currentList;
for (int i = 0;i < array.length;i++)
{
//in case your array doesn't contain the index_value at index 0
//check for the null case
if (array[i] == index_value || currentList == null)
{
currentList = new ArrayList<int>();
allLists.add(currentList);
}
else
{
currentList.add(array[i]);
}
}
if (allLists.size() > 0 && allLists.get(allLists.size() - 1).size() == 0)
{
allLists.remove(allLists.size() - 1);
}
What you should have is an ArrayList that contains ArrayLists that contain the numbers you are interested in. If the index_value is repeated twice in a row, however, you will end up with empty lists (which can be removed later). This includes the final list, which I automatically remove if it is empty (since your example lists the index_value as being at both the start and the end.
If you would like the output to be in arrays, you can just call .toArray() on the ArrayList
You might try the following strategy: look for your marker boundaries, form an array from each segment as encountered, and put result in a Vector (for example).
package com.splitter;
import java.util.Vector;
public class Splitter {
/**
* #param args
*/
public static void main(String[] args) {
int[] array = {10, 1,2,3,10,4,5,10,6,7,10,8,10};
Vector <int[]> result;
result = split(array,10);
for (int i = 0; i < result.size(); i++) {
int[] split = result.get(i);
System.out.println("Array " + i);
for (int j=0; j<split.length; j++) {
System.out.println(split[j]);
}
}
}
private static Vector<int[]> split(int[] array, int value) {
Vector<int[]> result = new Vector<int[]>();
int loc = 0;
int start = 0;
boolean isInside = false;
while (loc < array.length) {
if (array[loc] == value) {
if (isInside) { // make array from start to here
// make an array from start+1 to loc-1
System.out.println(" .." + start + " " + loc + " v=" + array[loc] );
int[] split = new int[loc - start - 1];
for (int i = 0; i < split.length; i++) {
split[i] = array[start+1+i];
}
result.add(split);
isInside = true;
}
start = loc;
isInside = true;
}
loc++;
}
return result;
}
}
I tried in NetBeans, debug, and works well.
The values will be stored like in a ArrayList with more ArrayLists inside, like this:
arrayOfIntList.get(0) = > 1,2,3
arrayOfIntList.get(0).get(0) -> 1
arrayOfIntList.get(0).get(1) -> 2
arrayOfIntList.get(0).get(2) -> 3
arrayOfIntList.get(1) = > 4,5
arrayOfIntList.get(1).get(0) -> 4
arrayOfIntList.get(1).get(1) -> 5
arrayOfIntList.get(2) = > 6,7
arrayOfIntList.get(2).get(0) -> 6
arrayOfIntList.get(2).get(1) -> 7
arrayOfIntList.get(3) = > 8
arrayOfIntList.get(3).get(0) -> 8
import java.util.ArrayList;
public class Javaprueba {
public static void main(String[] args) {
int[] myarray = {10,1,2,3,10,4,5,10,6,7,10,8,10};
int splitterInt = 10;
int j = 0;
int k = 0;
ArrayList<Integer> tempArray = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> arrayOfIntList = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<myarray.length; i++){
if(myarray[i] != splitterInt){
tempArray.add(j, myarray[i]);
j++;
}else{
if(tempArray.size() > 0){
arrayOfIntList.add(k, tempArray);
k++;
tempArray = new ArrayList<Integer>();
j=0;
}
}
if(i == myarray.length-1 && tempArray.size()>0){
arrayOfIntList.add(k, tempArray);
}
}
}
}

Finding multiple modes in an array of integers with 1000 elements

So I need a way to find the mode(s) in an array of 1000 elements, with each element generated randomly using math.Random() from 0-300.
int[] nums = new int[1000];
for(int counter = 0; counter < nums.length; counter++)
nums[counter] = (int)(Math.random()*300);
int maxKey = 0;
int maxCounts = 0;
sortData(array);
int[] counts = new int[301];
for (int i = 0; i < array.length; i++)
{
counts[array[i]]++;
if (maxCounts < counts[array[i]])
{
maxCounts = counts[array[i]];
maxKey = array[i];
}
}
This is my current method, and it gives me the most occurring number, but if it turns out that something else occurred the same amount of times, it only outputs one number and ignore the rest.
WE ARE NOT ALLOWED TO USE ARRAYLIST or HASHMAP (teacher forbade it)
Please help me on how I can modify this code to generate an output of array that contains all the modes in the random array.
Thank you guys!
EDIT:
Thanks to you guys, I got it:
private static String calcMode(int[] array)
{
int[] counts = new int[array.length];
for (int i = 0; i < array.length; i++) {
counts[array[i]]++;
}
int max = counts[0];
for (int counter = 1; counter < counts.length; counter++) {
if (counts[counter] > max) {
max = counts[counter];
}
}
int[] modes = new int[array.length];
int j = 0;
for (int i = 0; i < counts.length; i++) {
if (counts[i] == max)
modes[j++] = array[i];
}
toString(modes);
return "";
}
public static void toString(int[] array)
{
System.out.print("{");
for(int element: array)
{
if(element > 0)
System.out.print(element + " ");
}
System.out.print("}");
}
Look at this, not full tested. But I think it implements what #ajb said:
private static int[] computeModes(int[] array)
{
int[] counts = new int[array.length];
for (int i = 0; i < array.length; i++) {
counts[array[i]]++;
}
int max = counts[0];
for (int counter = 1; counter < counts.length; counter++) {
if (counts[counter] > max) {
max = counts[counter];
}
}
int[] modes = new int[array.length];
int j = 0;
for (int i = 0; i < counts.length; i++) {
if (counts[i] == max)
modes[j++] = array[i];
}
return modes;
}
This will return an array int[] with the modes. It will contain a lot of 0s, because the result array (modes[]) has to be initialized with the same length of the array passed. Since it is possible that every element appears just one time.
When calling it at the main method:
public static void main(String args[])
{
int[] nums = new int[300];
for (int counter = 0; counter < nums.length; counter++)
nums[counter] = (int) (Math.random() * 300);
int[] modes = computeModes(nums);
for (int i : modes)
if (i != 0) // Discard 0's
System.out.println(i);
}
Your first approach is promising, you can expand it as follows:
for (int i = 0; i < array.length; i++)
{
counts[array[i]]++;
if (maxCounts < counts[array[i]])
{
maxCounts = counts[array[i]];
maxKey = array[i];
}
}
// Now counts holds the number of occurrences of any number x in counts[x]
// We want to find all modes: all x such that counts[x] == maxCounts
// First, we have to determine how many modes there are
int nModes = 0;
for (int i = 0; i < counts.length; i++)
{
// increase nModes if counts[i] == maxCounts
}
// Now we can create an array that has an entry for every mode:
int[] result = new int[nModes];
// And then fill it with all modes, e.g:
int modeCounter = 0;
for (int i = 0; i < counts.length; i++)
{
// if this is a mode, set result[modeCounter] = i and increase modeCounter
}
return result;
THIS USES AN ARRAYLIST but I thought I should answer this question anyways so that maybe you can use my thought process and remove the ArrayList usage yourself. That, and this could help another viewer.
Here's something that I came up with. I don't really have an explanation for it, but I might as well share my progress:
Method to take in an int array, and return that array with no duplicates ints:
public static int[] noDups(int[] myArray)
{
// create an Integer list for adding the unique numbers to
List<Integer> list = new ArrayList<Integer>();
list.add(myArray[0]); // first number in array will always be first
// number in list (loop starts at second number)
for (int i = 1; i < myArray.length; i++)
{
// if number in array after current number in array is different
if (myArray[i] != myArray[i - 1])
list.add(myArray[i]); // add it to the list
}
int[] returnArr = new int[list.size()]; // create the final return array
int count = 0;
for (int x : list) // for every Integer in the list of unique numbers
{
returnArr[count] = list.get(count); // add the list value to the array
count++; // move to the next element in the list and array
}
return returnArr; // return the ordered, unique array
}
Method to find the mode:
public static String findMode(int[] intSet)
{
Arrays.sort(intSet); // needs to be sorted
int[] noDupSet = noDups(intSet);
int[] modePositions = new int[noDupSet.length];
String modes = "modes: no modes."; boolean isMode = false;
int pos = 0;
for (int i = 0; i < intSet.length-1; i++)
{
if (intSet[i] != intSet[i + 1]) {
modePositions[pos]++;
pos++;
}
else {
modePositions[pos]++;
}
}
modePositions[pos]++;
for (int modeNum = 0; modeNum < modePositions.length; modeNum++)
{
if (modePositions[modeNum] > 1 && modePositions[modeNum] != intSet.length)
isMode = true;
}
List<Integer> MODES = new ArrayList<Integer>();
int maxModePos = 0;
if (isMode) {
for (int i = 0; i< modePositions.length;i++)
{
if (modePositions[maxModePos] < modePositions[i]) {
maxModePos = i;
}
}
MODES.add(maxModePos);
for (int i = 0; i < modePositions.length;i++)
{
if (modePositions[i] == modePositions[maxModePos] && i != maxModePos)
MODES.add(i);
}
// THIS LIMITS THERE TO BE ONLY TWO MODES
// TAKE THIS IF STATEMENT OUT IF YOU WANT MORE
if (MODES.size() > 2) {
modes = "modes: no modes.";
}
else {
modes = "mode(s): ";
for (int m : MODES)
{
modes += noDupSet[m] + ", ";
}
}
}
return modes.substring(0,modes.length() - 2);
}
Testing the methods:
public static void main(String args[])
{
int[] set = {4, 4, 5, 4, 3, 3, 3};
int[] set2 = {4, 4, 5, 4, 3, 3};
System.out.println(findMode(set)); // mode(s): 3, 4
System.out.println(findMode(set2)); // mode(s): 4
}
There is a logic error in the last part of constructing the modes array. The original code reads modes[j++] = array[i];. Instead, it should be modes[j++] = i. In other words, we need to add that number to the modes whose occurrence count is equal to the maximum occurrence count

Removing duplicate elements from Array in Core Java

Without using collections,i have written a java program to remove duplicate integer element from an integer array,however the program is removing only one integer element and other integer element is left over.
Could you let me know how should i remove duplicate integer elements in the below core java program.In the below core java program i have to remove the duplicate integer element 5
Help provided will be appreciated.
Below is the Java code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DeleteElementFromArray {
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[10];
static int i, k, f, j = 0;
static int l = a.length;
void DeletElementInt() {
for (i = 0; i < l; i++) {
if (i != k) {
if (i < k) {
b[i] = a[i];
} else{
b[i - 1] = a[i];
}
}
}
}
public static void main(String[] args) {
DeleteElementFromArray d = new DeleteElementFromArray();
System.out.println("Array Elements are ");
for (i = 0; i < l; i++){
System.out.println(a[i]);
}
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.println("Enter the Element for Delete");
try {
String s = br.readLine();
f = Integer.parseInt(s);
for (i = 0; i < l; i++) {
if (f == a[i]) {
System.out.println("Delete Element found from given array");
k = i;
j++;
d.DeletElementInt();
}
}
l = l - 1;
System.out.println("New Array ");
for (i = 0; i < l; i++)
{
System.out.println(b[i]);
}
if (j == 0) {
System.out.println("Entered Element does not found from given array");
}
} catch (IOException e) {
System.out.println(e);
}
}
}
//output
/*
Array Elements are
5
1
2
3
4
5
7
8
9
10
Enter the Element for Delete
5
Delete Element found from given array
New Array
1
2
3
4
5
7
8
9
10
*/
Here is the fixed code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DelElem {
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[10];
static int f, i, k, j = 0;
static int l = a.length;
static void DeleteElementInt(int elementToDelete) {
j = 0;
for (int i = 0; i < l; i++)
if (a[i] != elementToDelete)
b[i - j] = a[i];
else
++j;
}
public static void main(String[] args) {
System.out.println("Array elements are:");
for (i = 0; i < a.length; i++)
System.out.println(a[i]);
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.print("Enter the element to be deleted: ");
try {
String s = br.readLine();
f = Integer.parseInt(s);
DeleteElementInt(f);
System.out.println("New array:");
for (i = 0; i < l - j; i++)
System.out.println(b[i]);
if (j == 0)
System.out.println("Entered element was not found in the given array");
} catch (IOException e) {
System.out.println(e);
}
}
}
//output
/*
Array elements are:
5
1
2
3
4
5
7
8
9
10
Enter the element to be deleted: 5
New array:
1
2
3
4
7
8
9
10
*/
First you have to sort your array. It will be much easier for you to remove the duplicates if you do. The Arrays class contains various methods (most of them are static) to manipulate arrays. Use Arrays.sort(array). If you're not allowed to, you have to use one of the many existing sorting algorithm. The simplest being Bubble sort.
Insert the first integer in your result array, and in a temporary variable which will contain the last inserted value. Parse the source array: if the current value is different than the temporary var, insert it in the result array (and update the temp var).
Be careful with the size of your return array.
is Arrays.sort() okay?
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[a.length];
Arrays.sort(a);
b[0]=a[0];
int bIndex = 1;
for(int aIndex = 1; aIndex < a.length; aIndex++) {
if(b[bIndex-1] != a[aIndex]) {
b[bIndex] = a[aIndex];
bIndex++;
}
}
int[] result = Arrays.copyOfRange(b, 0, bIndex);
if this is for educational purposes another interesting approach could be to construct a tree structure with the numbers and flatten the tree to an array when all inserts are done.
The first question when some one ask you to work with arrays should be. Do the order is important ?
Most problem with arrays can be solved by sorting it first and then the problem is reduced to trivial from complex as you always work on the same type of data. As Archimedes sad once "Give me a place to stand on, and I will move the Earth". The sort operation is that stand place.
When you sort your array, then you just need to traverse it and find that next item is equal to previous. This is trivial.
How ever if the order is important then we have a little bit harder task.
So first solution that pop i my mind is to create new point to stand. The rules are that array has items grater or equal then zero.
In this case we could do something like this.
We find the grates element in our source array.
We create a boolean array with size of grates item.
We move through each item of source list and
We check that boolean arrays position of value has false if so then we set it to true an print the result else we go to next item of source array.
The step 4 was simplified as we want to print the list. The technical aspect of returning new one with distinct values is trivial to.
So good luck.
import java.util.Scanner;
public class RemoveAllOccurences{
static int[] removeAll(int[] a,int n){
int[] dupl = new int[a.length];
for(int i = 0;i < dupl.length;i++){
dupl[i] = -999;
}
int index = 0;
//looping over,finding all occurrences of n and creating new array that does not contain n.
for(int i = 0;i < a.length;i++){
if(a[i] != n){
dupl[index++] = a[i];
}
}
//returning array with all duplicates removed.
return dupl;
}
public static void main(String[] args) {
int[] a = {3,5,5,5,3,6,5,3,3};
int numberToRemove;
System.out.println("the array values are:");
for(int i:a){
System.out.print(a[i]+"\t");
}
Scanner sc = new Scanner(System.in);
System.out.println("\nenter the number for which all occurences need to be deleted:");
numberToRemove = sc.nextInt();
int[] b = removeAll(a,numberToRemove);
System.out.println("After removing all occurences of "+numberToRemove);
for(int i:b){
if(i != -999)
System.out.print(i+"\t");
}
}
}
Below is my solution:
First step:- Iterate through array with nested loops to find duplicates
Second step:- If found duplicates copy all elements in new array except duplicate element.
Please find below code, any improvement would be appreciated.
public class DuplicateElements {
private static int[] arr = new int[]{3,2,4,4,5,3,8,2,4,9,10};
public static void main(String[] args) {
for(int i=0;i<arr.length;i++){
int arr_i = arr[i];
for(int j=0;j<arr.length;j++){
if(arr_i == arr[j] && i != j){
removeElement(j);
}
}
}
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+", ");
}
}
public static void removeElement(int position){
int[] intArr = new int[arr.length - 1];
for(int i=0;i<position;i++){
intArr[i] = arr[i];
}
for(int i=position+1;i<arr.length;i++){
intArr[i-1] = arr[i];
}
arr = intArr;
}
}
public static void main(String[] args) {
int a[]={1,4,3,2,6,5,7,3,5,4,2};
int b[]=new int[a.length];
Arrays.sort(a);
int j=0;
for(int i=0;i<a.length;i++){
while(i<a.length-1 && a[i]==a[i+1]){
a[i]=999; // This can be any tag which you are not going to have in your array
i++;
}
if(a[i]!=999)
b[j++]=a[i];
}
System.out.println(b);
}
Use:
package Array;
import java.util.Scanner;
public class DuplicateArrayElement {
//operation
void duplicate(int arr[],int size) {
int count=0;
for(int i=0;i<size-1;i++) {
for(int j=i+1;j<size;j++) {
if(arr[i]==arr[j]) {
arr[i]=0;
count++;
}
}
}
for(int i =0; i<size;i++) {
if(arr[i]!=0) {
System.out.println(" "+arr[i]);
}
}
System.out.println("Total duplicate number : "+count);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DuplicateArrayElement duplicateArrayElement = new DuplicateArrayElement();
try {
System.out.println("Enter the size of array:");
int size = input.nextInt();
int arr[] = new int[size];
System.out.println("Enter the elements: ");
for (int i = 0; i < size; i++) {
arr[i] = input.nextInt();
}
System.out.println("Orignal Array: ");
for (int i : arr) {
System.out.print(" " + i);
}
System.out.println("\nAfter removing duplicate values :");
duplicateArrayElement.duplicate(arr, size);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println(ex);
} finally {
input.close();
}
}
}

How do I sort numbers from an array into two different arrays in java?

I have to create a program that takes an array of both even and odd numbers and puts all the even numbers into one array and all the odd numbers into another. I used a for loop to cycle through all the numbers and determine if they are even or odd, but the problem I'm having is that since the numbers in the original array are random, I don't know the size of either the even or the odd array and therefore can't figure out how to assign numbers in the original array to the even/odd arrays without having a bunch of spots left over, or not having enough spots for all the numbers. Any ideas?
Try using an ArrayList. You can use
num % 2 == 0
to see if num is even or odd. If it does == 0 then it is even, else it is odd.
List<Integer> odds = new ArrayList();
List<Integer> evens = new ArrayList();
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evens.add(array[i]);
}
else {
odds.add(array[i]);
}
}
to convert the ArrayLists back to arrays you can do
int[] evn = evens.toArray(new Integer[evens.size()]);
(Note: untested code so there could be a few typos)
EDIT:
If you are not allowed to use ArrayLists then consider the following that just uses Arrays. It's not as efficient as it has to do two passes of the original array
int oddSize = 0;
int evenSize = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenSize++;
}
else {
oddSize++;
}
}
Integer[] oddArray = new Integer[oddSize];
Integer[] evenArray = new Integer[evenSize];
int evenIdx = 0;
int oddIdx = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenArray[evenIdx++] = array[i];
}
else {
oddArray[oddIdx++] = array[i];
}
}
You can do it without using arrays or any '%' Just a simple idea
input = new Scanner(System.in);
int x;
int y = 0; // Setting Y for 0 so when you add 2 to it always gives even
// numbers
int i = 1; // Setting X for 1 so when you add 2 to it always gives odd
// numbers
// So for example 0+2=2 / 2+2=4 / 4+2=6 etc..
System.out.print("Please input a number: ");
x = input.nextInt();
for (;;) { // infinite loop so it keeps on adding 2 until the number you
// input is = to one of y or i
if (x == y) {
System.out.print("The number is even ");
System.exit(0);
}
if (x == i) {
System.out.print("The number is odd ");
System.exit(0);
}
if (x < 0) {
System.out.print("Invald value");
System.exit(0);
}
y = y + 2;
i = i + 2;
}
}
Use a List instead. Then you don't need to declare the sizes in advance, they can grow dynamically.
You can always use the toArray() method on the List afterwards if you really need an array.
The above answers are correct and describe how people would normally implement this. But the description of your problem makes me think this is a class assignment of sorts where dynamic lists are probably unwelcome.
So here's an alternative.
Sort the array to be divided into two parts - of odd and of even numbers. Then count how many odd/even numbers there are and copy the values into two arrays.
Something like this:
static void insertionSort(final int[] arr) {
int i, j, newValue;
int oddity;
for (i = 1; i < arr.length; i++) {
newValue = arr[i];
j = i;
oddity = newValue % 2;
while (j > 0 && arr[j - 1] % 2 > oddity) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = newValue;
}
}
public static void main(final String[] args) {
final int[] numbers = { 1, 3, 5, 2, 2 };
insertionSort(numbers);
int i = 0;
for (; i < numbers.length; i++) {
if (numbers[i] % 2 != 0) {
i--;
break;
}
}
final int[] evens = new int[i + 1];
final int[] odds = new int[numbers.length - i - 1];
if (evens.length != 0) {
System.arraycopy(numbers, 0, evens, 0, evens.length);
}
if (odds.length != 0) {
System.arraycopy(numbers, i + 1, odds, 0, odds.length);
}
for (int j = 0; j < evens.length; j++) {
System.out.print(evens[j]);
System.out.print(" ");
}
System.out.println();
for (int j = 0; j < odds.length; j++) {
System.out.print(odds[j]);
System.out.print(" ");
}
}
Iterate through your source array twice. The first time through, count the number of odd and even values. From that, you'll know the size of the two destination arrays. Create them, and take a second pass through your source array, this time copying each value to its appropriate destination array.
I imagine two possibilities, if you can't use Lists, you can iterate twice to count the number of even and odd numbers and then build two arrays with that sizes and iterate again to distribute numbers in each array, but thissolution is slow and ugly.
I imagine another solution, using only one array, the same array that contains all the numbers. You can sort the array, for example set even numbers in the left side and odd numbers in the right side. Then you have one index with the position in the array with the separation ofthese two parts. In the same array, you have two subarrays with the numbers. Use a efficient sort algorithm of course.
Use following Code :
public class ArrayComparing {
Scanner console= new Scanner(System.in);
String[] names;
String[] temp;
int[] grade;
public static void main(String[] args) {
new ArrayComparing().getUserData();
}
private void getUserData() {
names = new String[3];
for(int i = 0; i < names.length; i++) {
System.out.print("Please Enter Student name: ");
names[i] =console.nextLine();
temp[i] = names[i];
}
grade = new int[3];
for(int i =0;i<grade.length;i++) {
System.out.print("Please Enter Student marks: ");
grade[i] =console.nextInt();
}
sortArray(names);
}
private void sortArray(String[] arrayToSort) {
Arrays.sort(arrayToSort);
getIndex(arrayToSort);
}
private void getIndex(String[] sortedArray) {
for(int x = 0; x < sortedArray.length; x++) {
for(int y = 0; y < names.length; y++) {
if(sortedArray[x].equals(temp[y])) {
System.out.println(sortedArray[x] + " " + grade[y]);
}
}
}
}
}

Java: Combination of recursive loops which has different FOR loop inside; Output: FOR loops indexes

currently recursion is fresh & difficult topic for me, however I need to use it in one of my algorithms.
Here is the challenge:
I need a method where I specify number of recursions (number of nested FOR loops) and number of iterations for each FOR loop. The result should show me, something simmilar to counter, however each column of counter is limited to specific number.
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
public void recursion(ArrayList<Integer> specs){
//number of nested loops will be equal to: specs.size();
//each item in specs, specifies the For loop max count e.g:
//First outside loop will be: for(int i=0; i< specs.get(0); i++)
//Second loop inside will be: for(int i=0; i< specs.get(1); i++)
//...
}
The the results will be similar to outputs of this manual, nested loop:
int[] i;
i = new int[7];
for( i[6]=0; i[6]<5; i[6]++){
for( i[5]=0; i[5]<7; i[5]++){
for(i[4] =0; i[4]<9; i[4]++){
for(i[3] =0; i[3]<2; i[3]++){
for(i[2] =0; i[2]<8; i[2]++){
for(i[1] =0; i[1]<9; i[1]++){
//...
System.out.println(i[1]+" "+i[2]+" "+i[3]+" "+i[4]+" "+i[5]+" "+i[6]);
}
}
}
}
}
}
I already, killed 3 days on this, and still no results, was searching it in internet, however the examples are too different. Therefore, posting the programming question in internet first time in my life. Thank you in advance, you are free to change the code efficiency, I just need the same results.
// ...
recursion (specs, specs.size () - 1);
// ...
public void recursion(ArrayList<Integer> specs, int startWith){
for (int i = 0; i < specs.get(startWith); i++) {
// ...
if (startWith - 1 >= 0)
recursion (specs, startWith - 1);
}
}
Your function also need to now the index of the specs array to use for iteration, and also the previous numbers that should be printed:
public void recursion(ArrayList<Integer> specs, int index, String output) {
if( index >= specs.size() ) {
System.out.println(output);
return;
}
for (int i = 0; i < specs.get(index); i++ )
recursion( specs, index+1, Integer.toString(i) + " " + output );
}
The you should call it like this:
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5);
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
recursion( specs, 0, "" );
Does this snippet give the output you want? (It is compileable and executeable)
import java.util.ArrayList;
import java.util.List;
public class SO {
static ArrayList<Integer> specs = new ArrayList<Integer>();
static int[] i;
public static void main(String[] args) throws Exception {
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
i = new int[specs.size()];
printMe(0, specs, i);
}
static void printMe(int depth, List<Integer> _specs, int[] i) {
if (_specs.isEmpty()) {
System.out.println(printI(i));
return;
} else {
for (int j = 0; j < _specs.get(0); j++) {
i[depth] = j + 1; // + 1 since you seems to want to go from 1 and not 0
printMe(depth + 1, _specs.subList(1, _specs.size()), i);
}
}
}
static String printI(int[] i) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < i.length; j++) {
sb.append(i[j]);
if (j < i.length - 1) {
sb.append(" ");
}
}
return sb.toString();
}
}
You can try this :
public static void loops(ArrayList<Integer> specs, int idx, StringBuilder res){
if(idx==specs.size()-1){
for (int i = 0; i < specs.get(idx); i++) {
System.out.println(i+" "+res);
}
}
else{
for(int i=0;i<specs.get(idx);i++){
res.insert(0,i+" ");
loops(specs,idx+1,res);
res.delete(0, 2);
}
}
}
And call with :
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
loops(specs,0, new StringBuilder());

Categories

Resources