2.9 Lab: Histogram
Complete the static method histogram() that takes an ArrayList of non-negative integers and returns an array of length m+1 whose ith entry is the number of times the integer i appeared in the list, where m is the largest entry in the list. For example, the histogram of the list: [5, 5, 0, 0, 5, 6, 2, 9, 7, 8, 5, 4, 1, 2, 1, 5, 0, 0, 2, 3,] is [4, 2, 3, 1, 1, 5, 1, 1, 1, 1]. Implement a linear time algorithm for this problem (it can be solved with just two passes over the data, one to find the max and one to find the counts). Only use ArrayList and arrays, i.e. do not use a HashMap or another collection.
import java.util.*;
import java.io.*;
public class Main
{
// Do not change method access or signature.
public static int[] histogram(ArrayList<Integer> a)
{
int[] array1 = a.stream().mapToInt(k->k).toArray();
Arrays.sort(array1);
int n = array1[array1.length-1];
int[] array = new int[n+1];
for(n=0;n<array.length;n++){
int k = getKCount(array1,n);
if(k == -1){
k = 0;
}
array[n]=k;
}
return array;
}
// Add other methods as needed
public static int getKCount(int[]a, int k){
int first = getFirstK(a,k,0,a.length-1);
int last = getLastK(a,k,0,a.length-1);
if(first>-1 && last>-1){
return last- first+1;
}
return -1;
}
public static int getFirstK(int a[], int k,int start, int end){
if(start>end){
return -1;
}
int mid =(start + end)/2;
int middata = a[mid];
if(middata == k){
if(mid>0 && a[mid-1]!=k || mid ==0){
return mid;
}else{
end = mid-1;
}
}
else if (middata<k){
start = mid+1;
}else if(middata>k){
end = mid -1;
}
return getFirstK(a,k,start,end);
}
public static int getLastK(int[]a, int k, int start, int end){
if(start>end){
return -1;
}
int mid =(start+end)/2;
int middata = a[mid];
if(middata == k){
if((mid==a.length-1||(mid<a.length-1&&(a[mid+1]!=k)))){
return mid;
}else{
start = mid+1;
}
}else if(middata<k){
start = mid+1;
}
else if(middata>k){
end = mid-1;
}
return getLastK(a,k,start,end);
}
// Do not change main
public static void main(String[] args)
{
// A scanner to read the values
Scanner cin;
if(args.length > 0)
{
try
{
cin = new Scanner(new FileReader(args[0]));
}
catch (FileNotFoundException e)
{
System.err.println("Unable to open " + args[0]);
System.exit(1);
return;
}
}
else
{
cin = new Scanner(System.in);
}
// An array list to hold the values
ArrayList<Integer> myList = new ArrayList<>();
// While there is more to read...
while(cin.hasNext())
{
// If the next token is an int...
if(cin.hasNextInt())
{
// Store if the value is not negative
int value = cin.nextInt();
if(value >= 0) myList.add(value);
}
else
{
// Otherwise skip it
cin.next();
}
}
// print the histogram
System.out.println(Arrays.toString(histogram(myList)));
}
}