java.awt.Queue cannot be accessed from outside package - java

The version of java: SDK 1.8.0_151
IDE: IDEA IntelliJ
import java.awt.Queue;
import java.util.LinkedList;
public class SimpleMovingAverage {
private final Queue<Double> window = new LinkedList<Double>();
private final int period;
private double sum;
public SimpleMovingAverage(int period) {
assert period > 0 : "Period must be a positive integer";
this.period = period;
}
public void newNum(double num) {
sum += num;
window.add(num);
if (window.size() > period) {
sum -= window.remove();
}
}
public double getAvg() {
if (window.isEmpty()) {return 0.0;} // technically the average is undefined
return sum / window.size();
}
public static void main(String[] args) {
double[] testData = {1, 2, 3, 4, 5, 5, 4, 3, 2, 1};
int[] windowSizes = {3, 5};
for (int windSize : windowSizes) {
SimpleMovingAverage ma = new SimpleMovingAverage(windSize);
for (double x : testData) {
ma.newNum(x);
System.out.println("Next number = " + x + ", SMA = " + ma.getAvg());
}
System.out.println();
}
}
}
The code above is coming from https://rosettacode.org/wiki/Averages/Simple_moving_average#Java
When I create a Class, called SimpleMovingAverage and copy the code from the above website, an error is reported.
'java.awt.Queue' is not public in 'java.awt'. Cannot be accessed from outside package
How to solve it?

You need java.util.Queue not java.awt.Queue, which can hold whatever you want
The java.awt package is about UI, graphics and images: Documentation, and the java.awt.Queue is here to hold java.awt.Event elements
For Improvement ONLY : for the implementation of a Circular FIFO, here some infos
Is there a fixed sized queue which removes excessive elements?
Basic implem of a CircularQueue
Which could give something like
public void newNum(double num) {
window.add(num);
}

Related

how to create a class that contain multiple medhods that can do operations, that can receive an arraylist of int,double,float,long,short

I want to create a class that contains multiple methods that can do mathematic operations. The method should be able to receive an ArrayList of int, double, float, long, short. I made the methods so that they can receive double ArrayLists because double is the parent of all the other number types from my understanding. Why can't my methods receive an ArrayList of Integers?
Here is my code:
import java.util.*;
import java.util.ArrayList;
class Operations <U extends Number>
{
// Function for calculating mean
public static double mean(ArrayList<Double> doubles)
{
double sum = 0;
for (int i = 0; i < doubles.size(); i++)
sum += doubles.get(i);
return (double)sum / (double)doubles.size();
}
// Function for calculating maximum value
public static double max(ArrayList<Double> doubles){
Collections.sort(doubles);
double max=0;
max=doubles.get(doubles.size()-1);
return max;
}
// Driver code
}
public class Main {
public static void main(String args[])
{
ArrayList<Double> doubles = new ArrayList<>(){
{add(4.3); add(5.9); add(2.3); add(9.5);}
};
ArrayList<Integer> integers = new ArrayList<>(){
{add(4); add(5); add(2); add(9);}
};
System.out.println(new Operations<Double>().mean(doubles));
// System.out.println(new Operations<Double>().mean(integers));
}
}
Here is an example implementation of mean that should work for all Numbers:
public static <T extends Number> double mean(List<T> numbers)
{
double sum = 0;
for (Number n : numbers)
sum += n.doubleValue();
return sum / (double)numbers.size();
}
Similarly max could look like:
public static <T extends Number> T max(List<T> numbers) {
T max = null;
for (T t : numbers) {
if (max == null || t.doubleValue() > max.doubleValue()) {
max = t;
}
}
return max;
}
Test:
#Test public void testNumbers() {
List<Double> d = Arrays.asList(4.3, 5.9, 2.3, 9.5);
System.out.println("doubles: mean=" + mean(d) + " max=" + max(d));
List<Integer> i = Arrays.asList(4, 5, 2, 9);
System.out.println("integers: mean=" + mean(i) + " max=" + max(i));
}
Output:
doubles: mean=5.5 max=9.5
integers: mean=5.0 max=9
Its wrong point:
double is the parent of all the other number types
For example ArrayList<Integer> can not to be casted to ArrayList<Double>
But you can try use somthing like that:
public U mean(List<U> values) {
You can get doubles from such values.

error when calling main method with parameters

I have the following code:
public class classroom{
public static void main(Integer[] args) {
int teachers = args[0];
int students = args[1];
int desks = args[2];
int computers = args[3];
double ratio = students/desks;
if (teachers == 1) {
if (computers >= students) {
if (ratio <= 6) {
System.out.println("this classroom is vald");
}
}
}
else {
System.out.println("this classroom is not valid");
}
}
}
I run the code as classroom.main(1, 2, 3, 4), and java returns the following error: 'identifier expected'. Any idea how I should solve this problem?
You should solve this problem call method as:
Classroom.main(new Integer[]{1, 2, 3, 4});
I think you need ... operator, Calling Classroom.main(1, 2, 3, 4) will require you to change the method Argument with three dot operator. By using Three dot operator ... You can pass integer arguments without explicitly creating array.
public class ClassRoom {
public static void main(String[] args) {
ClassRoom.main(1, 2, 3, 4);
}
private static void main(Integer... args) {
for (Integer i : args) {
System.out.println("Argument [ " + i + " ] = " + args[i-1]);
}
}
}
You should call the function by classroom.main(new Integer[] { 1, 2, 3, 4 }), instead of classroom.main(1, 2, 3, 4).
Because the function declares as classroom.main(Integer[] args), but not classroom.main(int a, int b, int c, int d).
Another advice: Java class name should use Camel Case for the Java naming convention.

How to find max number of participant who can perform?

I am trying to solve a question which has the following description:
At a time only one person can perform on the stage and arrival time and duration of each participant is given in the form of an array. Find the max number of participants who can perform.
Example:
arrival time: [1,3,3,5,7]
duration: [2,2,1,2,1]
answer would be 4, as 1-3; 3-5 or 3-4; 5-7; 7-8
So from this, I can find the exit time of each participant. How do I find max number of events possible, when there is overlap in timings.
The code I have tried is:
int count = 1;
for(int i=0;i<entry.size()-1;i++) {
if(entry.get(i) < exit.get(i+1)) {
count++;
}
}
return count;
I found the exit list using arrival + duration, but many tests are failing. The above example passes, but there might be instances where the overlapping time may have more participants possible.
I am not able to figure out how to proceed.
Updated answer as a new test case was added which made it clear the performers can be reordered if they have the same arrival time.
2nd update: Sort the input on the end time of each performer (arrival+duration).
Keep the endTime of the current performer. Only performers can perform which arrive after the end of the current performer.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class LifeGig {
public static class Performer {
int arrival, duration;
Performer(int arrival, int duration) {
this.arrival = arrival;
this.duration = duration;
}
#Override
public String toString() {
return "Performer [arrival=" + arrival + ", duration=" + duration + "]";
}
}
public List<Performer> program(int[] entry,int[] duration)
{
List<Performer> performers=new ArrayList<>();
for(int i=0;i<entry.length;i++)
{
performers.add(new Performer(entry[i],duration[i]));
}
Collections.sort(performers, new Comparator<Performer>() {
#Override
public int compare(Performer p1, Performer p2) {
return Integer.compare(p1.arrival+p1.duration, p2.arrival+p2.duration);
}
});
List<Performer> festival=new ArrayList<>();
System.out.println(performers);
int currentTime = 1;
for (Performer p:performers) {
if (p.arrival >= currentTime) {
currentTime = p.arrival+p.duration;
festival.add(p);
}
}
return festival;
}
public static void test1()
{
int[] entry = new int[] {1,3,3,5,7};
int[] duration = new int[] {2,2,1,2,1};
List<Performer> festival=new LifeGig().program(entry,duration);
System.out.println("Count (Expected=4): " + festival.size());
System.out.println("lineup:"+festival);
}
public static void test2()
{
int[] entry = new int[] {1, 1, 1, 1, 4};
int[] duration = new int[] {10, 3, 6, 4, 2};
List<Performer> festival=new LifeGig().program(entry,duration);
System.out.println("Count (Expected=2): " + festival.size());
System.out.println("lineup:"+festival);
}
public static void test3()
{
int[] entry = new int[] {1,2,3,4};
int[] duration = new int[] {10, 1,1,1,};
List<Performer> festival=new LifeGig().program(entry,duration);
System.out.println("Count (Expected=3): " + festival.size());
System.out.println("lineup:"+festival);
}
public static void main(String[] args) {
test1();
test2();
test3();
}
}
Since OP asked for a DP solution in a comment, and because it's not proven by the accepted answer that the greedy choice leads to an optimal solution, here's a DP solution. For any event, either it takes place or doesn't. The answer is the maximum of the two choices.
public class Solution {
private final List<Map.Entry<Integer, Integer>> events;
private final int[] startTimes;
private final Map<Integer, Integer> memo;
private static final Comparator<Map.Entry<Integer, Integer>> COMPARATOR =
Comparator.<Map.Entry<Integer, Integer>>comparingInt(Map.Entry::getKey)
.thenComparingInt(Map.Entry::getValue);
public Solution(int[] arrivals, int[] durations) {
events = IntStream.range(0, arrivals.length)
.mapToObj(i -> Map.entry(arrivals[i], arrivals[i] + durations[i]))
.sorted(COMPARATOR)
.collect(Collectors.toList());
startTimes = events.stream()
.mapToInt(Map.Entry::getKey)
.toArray();
memo = new HashMap<>();
}
private int loop(int i) {
if (i >= startTimes.length) {
return 0;
}
if (memo.containsKey(i)) {
return memo.get(i);
}
int ans = loop(i + 1);
int nextI = Arrays.binarySearch(startTimes, events.get(i).getValue());
if (nextI < 0) {
nextI = -nextI - 1;
}
ans = Math.max(ans, 1 + loop(nextI));
memo.put(i, ans);
return ans;
}
public static void main(String[] args) {
System.out.println(new Solution(new int[]{1, 3, 3, 5, 7}, new int[]{2, 2, 1, 2, 1}).loop(0));
System.out.println(new Solution(new int[]{1, 1, 1, 1, 4}, new int[]{10, 3, 6, 4, 2}).loop(0));
System.out.println(new Solution(new int[]{1, 2, 3, 4}, new int[]{10, 1, 1, 1}).loop(0));
}
}

PriorityQueue add Element will change the element, weird bug

public class Main {
public static class EE implements Comparable<EE> {
int x;
int[] rac;
public EE(int x, int[] rac) {
this.x = x;
this.rac = rac;
}
public int compareTo(EE that) {
if (this.x != that.x) return this.x - that.x;
else return this.rac[2] = that.rac[2];
}
}
public static void main(String[] args) {
int [][] ary = {
{1,1,3,3},
{1,3,2,4},
{2,3,3,4}};
PriorityQueue<EE> pq = new PriorityQueue<EE>();
for (int[] rec : ary) {
EE e1 = new EE(rec[0], rec);
EE e2 = new EE(rec[2], rec);
pq.add(e1);
pq.add(e2);
}
}
This piece of code I'm running, everything is fine but when the second for loop is entered, rec is [1, 3, 2, 4] initially, when pq.add(e1) get called, value of rec will become [1, 3, 3, 4] anyone can explain why this happens? Thank you in advance!
The preoblem is in comapreTo method:
return this.rac[2] = that.rac[2];
It's returning always the latter that.rac[2]. It should be:
return this.rac[2] == that.rac[2];

get the lowest value of a double[]

i wrote the following codes
my aim is to get the lowst value of doble[] absOfSub but it gives the following exception
at line compared= Double.compare(d2, d1);
Exception in thread "main" java.lang.StackOverflowError
why overflow and how to fix it?
EDIT
public class TestThe {
static double[] absOfSub = new double[5];
private static int index=0;
private static int compare(int currentIdx, int minIdx) {
if(index < absOfSub.length) {
if(absOfSub[currentIdx] < absOfSub[minIdx]) {
compare(currentIdx + 1, currentIdx);
} else {
compare(currentIdx + 1, minIdx);
}
}
return minIdx;
}
public static void main(String[] args) {
absOfSub[0]=1000;
absOfSub[1]=810;
absOfSub[2]=108;
absOfSub[3]=130;
absOfSub[4]=110;
double result;
int inndex= compare(0,1);
System.out.println(absOfSub[inndex]);
}
}
How about this simple and elegant solution?
static double min(double... ds) {
double min = Double.POSITIVE_INFINITY;
for (double d : ds) min = Math.min(min, d);
return min;
}
public static void main(String[] args) {
System.out.println(min(-5.2, 0, -10.1, 3));
}
Recursive solution (not recommended!):
static double minRecur(double... ds) {
return minRecur(ds, 0, Double.POSITIVE_INFINITY);
}
static double minRecur(double[] ds, int i, double runningMin) {
return (i < 0 || i >= ds.length)?
runningMin : minRecur(ds, i + 1, Math.min(runningMin, ds[i]));
}
You don't change the value of index inside your method. So this recursive method call won't stop at all.
You never manipulate the value of the index variable. You see another reason why people should try to limit the number of static variables they use. Let me try to help you:
public class TestThe {
private static double[] absOfSub = new double[5];
private static void compare(int currentIdx, int minIdx) {
if(currentIdx < absOfSub.length) {
if(absOfSub[currentIdx] < absOfSub[minIdx]) {
return compare(currentIdx + 1, currentIdx);
} else {
return compare(currentIdx + 1, minIdx);
}
} else {
return minIdx;
}
}
public static void main(String[] args) {
absOfSub[0] = 10;
absOfSub[1] = 810;
absOfSub[2] = 108;
absOfSub[3] = 130;
absOfSub[4] = 110;
System.out.println("The minimum value is: " + absOfSub[compare(0, 0)]);
}
}
EDIT Some more notes:
always specify the attribute accessor as private, when this is the intention
always format your code
when you write recursion, make sure you always change something for every consequent call and that it gets you closer to the ending condition.
double primitive type itself defines a comparison operator, no need to use Double.compare in your case.
You don't actually change the index variable, so the recursion will never end. But there is a lot more wrong with this.
An easy generic way to find the minimal value in an array, without using recursion:
int min = Integer.MAX_VALUE;
for( int i = 0; i < array.length; i++ ) {
// Math.min returns the lower value of the two arguments given
min = Math.min( min, array[i] );
}
return min;
This could be easily adapted to fit your needs.
Index in each routine is having either 0 or 1 or 2 as the value.

Categories

Resources