I am trying to find out the majority Element in an array ad this code is working fine when I am checking with elements less than size. But it is giving me arrayindexoutofbound exception whenever any element is equal to size of array. Please let me know how to resolve this.
public class MajorityElement {
public static void main(String[] args) {
int a[]={2,2,7,5,2,2,6};
printMajority(a, 7);
}
//1st condition to check if element is in majority.
public static int findCandidate(int a[], int size){
int maj_index=0;
int count =1;
int i;
size=a.length;
for(i=1;i<a.length;i++ ){
if(a[maj_index]==a[i])
count++;
else
count--;
if(count==0)
{
maj_index=a[i]; //current element takes max_inex position.
count =1;
}
}
return a[maj_index];
}
public static boolean isMajority(int a[], int size, int cand){
int i, count =0;
for(i=0;i<a.length;i++)
{
if(a[i]==cand)
count++;
}
if(count>size/2){
return true;
}
else {
return false;
}
}
private static void printMajority(int a[],int size){
size=a.length;
int cand=findCandidate( a, 7);
if(isMajority(a,size,cand))
System.out.printf("%d",cand);
else
System.out.println("no such element as majority");
}
}
The problem is in the maj_index=a[i]; line. You take the value of one of the cells of the array and assign it to maj_index which is subsequently used as an index into the array (see a[maj_index] == a[i]). Thus, if the value at that position was larger than the size of the array an out-of-bounds situation will occur.
Here's your code slightly revised. In particular, I got rid of the maj_index variable so that the index vs. value mixup cannot happen. I also used a for-each loop for (int current : a) instead of the for-loop for(int i = 0; i < a.length; ++i). Finally, I eliminated the the size parameter (no need to pass it, it can be inferred from the array itself via a.length)
public class MajorityElement {
// 1st condition to check if element is in majority.
public static int findCandidate(int a[]) {
int cand = a[0];
int count = 1;
for (int i = 1; i < a.length; i++) {
if (cand == a[i])
count++;
else
count--;
if (count == 0) {
cand = a[i];
count = 1;
}
}
return cand;
}
public static boolean isMajority(int a[], int cand) {
int count = 0;
for (int current : a) {
if (current == cand)
count++;
}
return count > a.length / 2;
}
private static void printMajority(int a[]) {
int cand = findCandidate(a);
if (isMajority(a, cand))
System.out.printf("%d", cand);
else
System.out.println("no such element as majority");
}
public static void main(String[] args) {
int a[] = { 9, 7, 9, 5, 5, 5, 9, 7, 9, 9, 9, 9, 7 };
printMajority(a);
}
}
Problem is with your :
for(i=1;i<a.length;i++ ){
if(a[maj_index]==a[i])
count++;
else
count--;
if(count==0)
{
maj_index=a[i]; //current element takes max_inex position.
count =1;
}
}
return a[maj_index];
here you are getting the value as like :a[maj_index] for a test data int a[]={2,1,8,8,8,8,6}; the elemnt 8 is the major but a[maj_index] is invalid which is causing the issue,
Instead Complete code can be like below:
public class TestMajor {
/**
* #param args
*/
public static void main(String[] args) {
int a[]={2,1,8,8,8,8,6};
printMajority(a, 7);
}
//1st condition to check if element is in majority.
public static int findCandidate(int a[], int size){
int test = a[0];
int count =1;
int i;
size=a.length;
for(i=1;i<a.length;i++ ){
if(test ==a[i])
count++;
else
count--;
if(count==0)
{
test =a[i]; //current element takes max_inex position.
count =1;
}
}
return test;
}
public static boolean isMajority(int a[], int size, int cand){
int i, count =0;
for(i=0;i<a.length;i++)
{
if(a[i]==cand)
count++;
}
if(count>size/2){
return true;
}
else {
return false;
}
}
private static void printMajority(int a[],int size){
size=a.length;
int cand=findCandidate( a, 7);
if(isMajority(a,size,cand))
System.out.printf("%d",cand);
else
System.out.println("no such element as majority");
}
}
Majority Element in an Array using Java 8 OR Find the element appeared max number of times in an array :
public class MajorityElement {
public static void main(String[] args) {
int[] a = {1,3,4,3,4,3,2,3,3,3,3,3};
List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
Map<Integer, Long> map = list.parallelStream()
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println("Map => " + map);
//{1=1, 2=1, 3=8, 4=2}
map.entrySet()
.stream()
.max(Comparator.comparing(Entry::getValue))//compare the values and get the maximum value
.map(Entry::getKey)// get the key appearing maximum number of times
.ifPresentOrElse(System.out::println,() -> new RuntimeException("no such thing"));
/*
* OUTPUT : Map => {1=1, 2=1, 3=8, 4=2}
* 3
*/
System.out.println("...............");
// A very simple method
//method 2
Integer maxAppearedElement = list.parallelStream().max(Comparator.comparing(Integer::valueOf)).get();
System.out.println(maxAppearedElement);
}//main
}
Related
I am working on Replacement Selection sort project but i keep getting the error Exception in thread main Java.lang.ArrayIndexOutOfBoundsException:10 at ReplacementSelection.swap(ReplacementSelection.java:42) at ReplacementSelection.siftDown(ReplacementSelection.java:69) at Replacement..
class ReplacementSelection {
static int[] array = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
public static void sort() {
System.out.println("before:" + Arrays.toString(array));
for (int i = array.length/2; i >= 0; i--) {
siftDown(i);
}
int count = array.length-1;
while (count > 0)
{
swap(array[0], array[count]);
--count;
siftDown(0);
}
System.out.println("after:" + Arrays.toString(array));
}
public static void swap(int i, int j)
{
int tmp;
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
public static void siftDown(int index)
{
int count = array.length;
// Left child is at index*2+1. Right child is at index*2+2;
while (true)
{
// first find the largest child
int largestChild = index*2+1;
// if left child is larger than count, then done
if (largestChild >= count)
{
break;
}
// compare with right child
if (largestChild+1 < count && array[largestChild] < array[largestChild+1])
{
++largestChild;
}
// If item is smaller than the largest child, then swap and continue.
if (array[index] < array[largestChild])
{
swap(array[index], array[largestChild]);
index = largestChild;
}
else
{
break;
}
}
}
public static void main(String[] args){
ReplacementSelection a = new ReplacementSelection();
a.sort();
}
}
You have written a swap method which takes indices as arguments. However, you pass it the values in the array at those indices instead of the indices themselves:
swap(array[0], array[count]);
and
swap(array[index], array[largestChild]);
To fix the exception error just pass the indices to the method:
swap(0, count);
and
swap(index, largestChild);
As #Pajacar123 mentioned, you should learn to use debugger.
In line
swap(array[index], array[largestChild]);
You are passing value from array which is at last index of table(index 9 value 10). Then when in method sawp in line array[i] = array[j];
j value is 10 while max index of table is 9. That causes exception. You are trying to refer to not existing elemnt.
I'm new to recursion, can you please tell me why the output of this function is = 3
public class Rekursion2 {
public static void main(String[] args) {
int[] arr = {6,1,2,3,1,100,76};
System.out.println(maximum(arr,3));
}
static int maximum(int[] arr, int i) {
int max = 0;
if(i < 0 || i > arr.length) {
return max;
}
if(arr[i] > max) max=arr[i];
maximum(arr, i-1);
return max;
}
}
You execute maximum with an index of 3.
3 is in the bounds of the array, so the method will not stop at this point.
arr[3] is 3(fourth element) which is bigger that max(0), so max will be assigned to 3.
After this, the method is called recursively but it does not change anything(you don't do anything with the return value).
At the end, max(3) is returned.
I am trying to implement selection sort recursively in java, but my program keeps throwing an ArrayIndexOutOfBounds exception. Not sure what I am doing wrong. Recursion is very hard for me. Please help! I am a beginner.
public static int[] selection(int[] array) {
return sRec(array, array.length - 1, 0);
}
private static int[] sRec(int[] array, int length, int current) {
if (length == current) { //last index of array = index we are at
return array; //it's sorted
}
else {
int index = findBig(array, length, current, 0);
int[] swapped = swap(array, index, length - current);
return sRec(swapped, length - 1, current);
}
}
private static int[] swap(int[] array, int index, int lastPos) {
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = array[temp];
return array;
}
private static int findBig(int[] array, int length, int current, int biggestIndex) {
if (length == current) {
return biggestIndex;
}
else if (array[biggestIndex] < array[current]) {
return findBig(array, length, current + 1, current);
}
else {
return findBig(array, length, current + 1, biggestIndex);
}
}
public static void main (String [] args) {
int[] array = {8,3,5,1,3};
int[] sorted = selection(array);
for (int i = 0; i < sorted.length; i++) {
System.out.print(sorted[i] + " ");
}
}
Try changing this in your Swap method :
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = array[temp];
return array;
to this :
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = temp;
return array;
You have already gotten the value you want to assign to the array , when you add that to the array it is searching in that specific index ,
For Example :
You wanted to enter the value 8 to your Array
Instead of doing
array[index] = 8
You were doing
array[index] = array[8]
That was causing your OutOfBounds Exception.
I tested your code and it did not sort even after having fixed the "Out Of bound Exception". I've changed your method findBig in order to make it work. The principle is :
If the length of the sub array is one (begin==end) then the biggest element is array[begin]
divide the array by half
Recusively find the index of the biggest element in the left side
Recursively find the index if the biggest element in the right side
Compare the biggest element of the left side with that of the right side of the array and return the index of the biggest of both.
This leads to the following code which sort the array in a decreasing order:
public class Sort {
public static int[] selection(int[] array) {
return sRec(array,0);
}
private static int[] sRec(int[] array, int current) {
if (current == array.length-1) { //last index of array = index we are at
return array; //it's sorted
}
else {
int indexOfBiggest = findBig(array, current,array.length-1);
int[] swapped = swap(array, indexOfBiggest, current );
return sRec(swapped, current+1);
}
}
private static int[] swap(int[] array, int index, int lastPos) {
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = temp;
return array;
}
private static int findBig(int[] array, int begin, int end) {
if (begin < end) {
int middle = (begin+end)/2;
int biggestLeft = findBig(array,begin,middle);
int biggestRight = findBig(array,middle+1,end);
if(array[biggestLeft] > array[biggestRight]) {
return biggestLeft;
}else {
return biggestRight;
}
}else {
return begin;
}
}
public static void main (String [] args) {
int[] array = {8,3,5,1,3};
// System.out.println(findBig(array,0,array.length-1));
int[] sorted = selection(array);
for (int i = 0; i < sorted.length; i++) {
System.out.print(sorted[i] + " ");
}
}
}
running into a silly error and I just don't see it. I've been looking at this for a while and don't see what I'm missing. I am recursively searching an array for a specific target number but once I get up to element [7] it begins returning -1. Thanks for taking a look fellas/ladies!
public static void main(String[] args)
{
int[] a = {1,25,2,6,4,3,23,30,32,14,11,8};
Arrays.sort(a);
int target = a[7];
int first = a[0];
int last = a.length;
for(int i=0;i<a.length;i++)
{
System.out.print(" "+a[i]);
}
System.out.println("\n"+binarySearch(target,first,last,a));
}
public static int binarySearch(int target,int first, int last, int[] a)
{
int result;
if(first>last)
return -1;
else
{
int mid = (first+last)/2;
if(target == mid)
result = mid;
else if(target<a[mid])
result = binarySearch(target,first,last-1,a);
else
result = binarySearch(target,mid+1,last,a);
}
return result;
}
In several places you fail to accurately distinguish between the value in an index of an array and the index itself.
This: a[i] gets the value at the ith element
This: i is simply an index, i
With that in mind, here is a fixed version of your code. See my comments in the code for some specific errors I fixed:
public static void main(String[] args)
{
int[] a = {1,25,2,6,4,3,23,30,32,14,11,8};
Arrays.sort(a);
int target = a[7];
//here you want the index of the first location to search, not the value in that index
//so you use 0 instead of a[0]
int first = 0;
//the last element index is length-1, not length, since arrays are 0-based
int last = a.length - 1;
for(int i=0;i<a.length;i++)
{
System.out.print(" "+a[i]);
}
System.out.println("\n"+binarySearch(target,first,last,a));
}
public static int binarySearch(int target,int first, int last, int[] a)
{
int result;
if(first>last)
return -1;
else
{
int mid = (first+last)/2;
//here you need to check if the target is equal to the value at the index mid
//before you were checking if the target was equal to the index, which was never true
if(target == a[mid])
//you want to return the value at the target, not the index of the target
//so use a[mid] not mid
result = a[mid];
else if(target<a[mid])
//here you want to search from first to mid-1
//before you were searching from first to last-1, which is not correct binary search
result = binarySearch(target,first,mid - 1,a);
else
result = binarySearch(target,mid + 1,last,a);
}
return result;
}
i have to get a sequence of numbers and count how many times it takes and then put it into an array so i can sort the array and look for the 10th largest. I can get the count but cant seem to fill the array, i either put in the final count at every index in the array or i just increase the value of the array at index 0 to the count of all numbers, can anyone help.
public class seBuilder
{
//int count=0;
//int [] myArray= new int[10];
public static void main (String args[])
{
int count=0;
int [] myArray= new int[13];
int z=0;
for(int i=2;i<=myArray.length;i++)
{
z=valuegetter(i);
System.out.println(z);
}
//arraycounter(myArray, z);
}
public static int valuegetter(int num)
{
int count=0;
do// do while loop
{
//if its an odd number
if(num%2==1){
num=(num*3)+1;//do this from the question
count++;// add one to count
}
//if num is 2 this will catch and make the code break out
else if(num==2){
//devide num by 2, this will give you 1 allways
System.out.println(num/2);
count++;//adds 1 again
}
else
{
num=num/2;//this will use if number is even
count++;//adds one to count
}
}
while(num>2);//the condition to jump out of loop
//System.out.println("there are "+count+" sequences in that mumber");
return count;
}
public static int[] arraycounter(int myArray[], int count)
{
for(int i=0;i<=myArray.length-1;i++)
{
myArray[i]=count;
System.out.println(" "+myArray[i]);
}
return myArray;
}
public static int tenhigh()
{
}
}
Try to change your main to this:
public static void main (String args[])
{
int count=0;
int [] myArray= new int[13];
int z=0;
for(int i=2;i<=myArray.length;i++) {
z=valuegetter(i);
System.out.println(z);
arraycounter(myArray, z, i);
}
for (int i=0; i < myArray.length; i++) {
System.out.print(myArray[i] + ", ");
}
}
Also change your arrayCounter method to this:
public static int[] arraycounter(int myArray[], int count, int i)
{
int j = i - 2;
myArray[j] = count;
return myArray;
}
If you want to fill an array with a given value, use Arrays.fill, from the java.utils.Arrays class.