I am trying to solve this question from talent buddy.
http://www.talentbuddy.co/challenge/52a9121cc8a6c2dc91481f8d5233cc274af0110af382f40f
My code compiles and runs for small input, but is giving wrong ans for the following input-
http://tb-eval4.talentbuddy.co/5411559648d3e7eb5100024191810645628720530000.html
My Code is as follows -
import java.util.*;
class MyClass {
public void tweets_per_second(Integer[] tps, Integer k) {
PriorityQueue<Integer> pq =new PriorityQueue<Integer>(k, new Comparator<Integer>(){
public int compare(Integer i1, Integer i2){
if (i1.intValue()< i2.intValue()){
return 1;
}
else if(i1.intValue() ==i2.intValue()){
return 0;
}
else {
return -1;
}
}
});
for(int i=0;i<tps.length;i++){
if (pq.size()<=k){
pq.add(tps[i]);
System.out.println(pq.peek());
}
else{
pq.remove(tps[i-k]);
pq.add(tps[i]);
System.out.println(pq.peek());
}
}
}
public static void main(String[] args) {
MyClass t = new MyClass();
Integer[] tps = {6,9,4,7,4,1};
t.tweets_per_second(tps, 3);
}
}
Can someone please let me know what am I doing wrong? Any help will be appreciated. Thanks.
The code is entirely correct. At the end of the page you can see the following:
Error: your code didn't finish in less than 2 seconds.
Which tells you all you need to know.
As to why your code is slow - while using PriorityQueue or any built in collections etc is overall a good idea, it is very much not so in this case. I don't want to make educated guesses about how it's implemented, but one of add, remove, peek is not O(1) and eats up your time.
Related
I'm creating a program in java to store top 10 highest scores. So, i'm using Array in it. I have question in my mind whether what is to be used singly linked list or array in the program to avoid complexity of the code and make program more efficient.
private int numEntries = 0;
private GameEntry[] board;
public Scoreboard(int capacity){
board = new GameEntry[capacity];
}
public void add(GameEntry e){
int newScore = e.getScore();
if(numEntries<board.length||newScore>board[numEntries-1].getScore()){
if(numEntries<board.length){
numEntries++;
}
int j=numEntries-1;
while(j>0&&board[j-1].getScore()<newScore){
board[j]=board[j-1];
j--;
}
board[j]=e;
}
}
In such cases no need to think too much about performance (unless it is huge numbers), you should write as clear as possible, understandable code. Later you may tune it, but first make sure it logically correct and you really need performance improvement.
Also you don't need to implement sorting, use existing utilities.
I would do it like this:
List<GameEntry> arr = new ArrayList<>();
Comparator<GameEntry> cmp = Comparator.comparingInt(a -> a.getScore());
public void add(GameEntry e) {
arr.add(e);
Collections.sort(arr, cmp.reversed());
while(arr.size() > capacity) {
arr.remove(arr.size()-1);
}
}
What is the difference between these two ways of dealing with stacks and queues? What are the both called?
First way:
import java.util.Arrays;
public class StackMethods {
private int top;
int size;
int[] stack ;
public StackMethods(int arraySize){
size=arraySize;
stack= new int[size];
top=-1;
}
public void push(int value){
if(top==size-1){
System.out.println("Stack is full, can't push a value");
}
else{
top=top+1;
stack[top]=value;
}
}
public void pop(){
if(!isEmpty())
top=top-1;
else{
System.out.println("Can't pop...stack is empty");
}
}
public boolean isEmpty(){
return top==-1;
}
public void display(){
for(int i=0;i<=top;i++){
System.out.print(stack[i]+ " ");
}
System.out.println();
}
}
Second way:
public class StackReviseDemo {
public static void main(String[] args) {
StackMethods newStack = new StackMethods(5);
newStack.push(10);
newStack.push(1);
newStack.push(50);
newStack.push(20);
newStack.push(90);
newStack.display();
newStack.pop();
newStack.pop();
newStack.pop();
newStack.pop();
newStack.display();
}
}
Also are they correct? trying to learn these well, but explanations across the internet are vague about these..
I'm not 100% sure what you mean with two ways.
Looking at your first code snippet, we can see that you are declaring the class StackMethods. In the second one you are instantiating an object of the class StackMethods.
So all you do in the main-method of your second code snippet is to create an object which is calling the methods push(), pop() and display() you declared in the class above. You didn't actually implement two datastructures, but just a basic stack.
The good news is, over all you have grasped the concepts of stacks, since your implementation of the class 'StackMethods' is correct overall.
In regards to what the difference between a Queue and a Stack is, this question might help you:
In case this didn't answer your question and I simply misunderstood it, please just comment and let me know so I can try to help you out a little better.
The error i am having here is a infinite or near infinite loop in my method calls and class's creating other class's constructors. What my program is trying to do is semi-randomly generate survey results based off actual statistics. I would highly appreciate not only some insight in whats going wrong here. But some advice and pointers on how to prevent this from happening and ways to analyze the error messages by myself. I get how some of the work but like i stated below i am new to programming im a freshman in college so programming is new to me. Thanks in advance and sorry for my previous post, thought i would take the time to give you guys an appropriate one.
Im new to programming this is my 2nd project ive done on my own so im sorry if its not the best.
This is my Test class:
public Tester()
{
randomGenerator = new Random();
probability = new Probability();
stats = new Statistics();
double chance = randomGenerator.nextDouble();
double gender = probability.getProbabilityOfMale();
if(chance > gender)
{
male = false;
stats.incrementFemale();
}else{
male = true;
stats.incrementMale();
}
age = randomGenerator.nextInt(49)+16;
int range = stats.getNumberOfQuestion();
for(int i=0;i<range;i++)
{
probabilities = probability.probOfAnswer(i);
answers = probability.getAnswers(i);
chance = randomGenerator.nextDouble();
int size = probabilities.size();
for(int j=0;j<size;j++)
{
double qTemp = chance - probabilities.get(j);
if(qTemp <= 0.0)
{
Answer aTemp = answers.get(j);
aTemp.incrementCounter();
answers.set(j,aTemp);
}
}
}
}
Statistics class:
public ArrayList<Answer> getAnswers(int index)
{
temp = survey.getAnswers(index);
return temp;
}
public int getMale()
{
return male;
}
public int getFemale()
{
return female;
}
public int getNumberOfQuestion()
{
return numberOfQuestion;
}
public void incrementNumberOfQuestion()
{
numberOfQuestion++;
}
public void incrementMale()
{
male++;
}
public void incrementFemale()
{
female++;
}
and probability class:
public Probability()
{
stats = new Statistics();
probOfAnswer = new ArrayList<Double>(0);
}
public ArrayList<Double> probOfAnswer(int index)
{
temp = stats.getAnswers(index);
int size = temp.size();
for(int i=0;i<size;i++)
{
aTemp = temp.get(i);
for(int j=0;j<size;j++)
{
Answer aTemp = temp.get(j);
sum += (double)aTemp.getCounter();
}
double number = (double)aTemp.getCounter();
probOfAnswer.add(number/sum);
sum = 0;
}
return probOfAnswer;
}
public ArrayList<Answer> getAnswers(int index)
{
temp = stats.getAnswers(index);
return temp;
}
public ArrayList<Double> getProbofAnswer()
{
return probOfAnswer;
}
public void probabilityOfMale()
{
double male = (double)stats.getMale();
double female = (double)stats.getFemale();
probabilityOfMale = male / (male + female);
}
public double getProbabilityOfMale()
{
return probabilityOfMale;
}
These are the only real important parts where the loop exsists the rest of the code is not needed to be uploaded.
Im having difficulty uploading my error message on this site its not accepting it as code in the code insert, then it wont let me submit the message afterwards so im going to upload the code elseware and link it.
http://forum.overdosed.net/index.php/topic/56608-this-is-unimportant/
But i dont know how long that forum will let me keep that post there ><
at Question.<init>(Question.java:17)
at Survey.addQuestion(Survey.java:23)
at Statistics.<init>(Statistics.java:52)
at Question.<init>(Question.java:17)
at Survey.addQuestion(Survey.java:23)
at Statistics.<init>(Statistics.java:52)
at Probability.<init>(Probability.java:19)
You need to check why Question is creating Statistics object and again Statistics is trying to create Question object leading to infinite recursion. As the line numbers are given you can take a look at corresponding lines.
Judging by the stack trace, the problem lies in three parts which you haven't shown us - the Question and Statistics constructors and the Survey.addQuestion method:
From the stack trace:
at Survey.addQuestion(Survey.java:23)
at Statistics.<init>(Statistics.java:52)
at Question.<init>(Question.java:17)
at Survey.addQuestion(Survey.java:23)
at Statistics.<init>(Statistics.java:52)
at Question.<init>(Question.java:17)
So your Question constructor is calling the Statistics constructor. But the Statistics constructor is then calling Survey.addQuestion, which is in turn calling the Question constructor.
It feels to me like there's much more construction going on than is really useful. Why would a Statistics constructor need to add anything to a survey? I wouldn't expect a Statistics class to even know about surveys and questions.
It's entirely possible that a lot of this can be fixed by passing a reference to an existing object to the constructors - so the Probability constructor may be better taking a Statistics reference in its constructor and using that for its stats field than creating a new Statistics object itself. It's hard to say without knowing what these classes are really meant to represent though... which may be part of the problem. Do you have a firm grasp of what the responsibility of each class is? Think about that carefully before making any code changes.
We don't have the relevant source code, but the error message says what's wrong:
Tester creates a Probability
Probability constructor creates a Statistics
Statistics constructor calls Survey.addQuestion()
addQuestion() creates a Question
Question creates a Statistics (goto 3 and loop infinitely)
I think you should probably pass objects around rather than creating them each time.
import java.math.BigInteger;
import java.util.HashMap;
/**
*
* #author cypronmaya
*/
public class test {
static HashMap<Integer, BigInteger> cache = new HashMap<Integer, BigInteger>();
public static void main(String[] args) {
System.out.println(factorial(20000));
}
public static BigInteger factorial(int n) {
BigInteger ret;
if (n == 0) {
return BigInteger.ONE;
}
if (null != (ret = cache.get(n))) {
return ret;
}
ret = BigInteger.valueOf(n).multiply(factorial(n - 1));
cache.put(n, ret);
return ret;
}
}
Exception in thread "main" java.lang.StackOverflowError at
java.util.HashMap.get(Unknown Source)
Hi,
Why am i getting stackoverflow exception to this program?
i know that stackoverflow usually means you have an infinite loop,
but this works fine when i'm using 10000 or some other numbers lesser, wht becomes suddenly infinite with big numbers?
A StackOverflowError occurs when the call stack overflows. This happens when you have too many nested calls (because each call requires space to be reserved on the stack, and it's a finite size). I guess in your case, 20000 is too many.
You can modify the stack size of the JVM with the -Xss flag. But I'd suggest that you find a different way to compute a factorial.
The recursive function each time that is called create a new pointer in the stack, so with an high number of calls of a recursive function you can get a StackOverflow Exception ...
Tip : replace the recursive function with a loop to resolve.
The reason is that your factorial function is recursive and this is NOT tail recursion.
It means that every time you call the "factorial" function this call is put to the stack.
I have no idea if Java compiler can generate tail recursion calls at all, but if it can, you can simply refactor your function to a tail-call way. Otherwise just avoid recursion (a good practice in imperative languages anyway).
Non-recursive versions (not so much as compiled - this is Stack Overflow). There will be clearer ways to write this.
public class Test {
private static final Object lock = new Object();
private static final List<BigInteger> cache = new ArrayList<>(
Arrays.asList(BigInteger.ONE)
);
public static void main(String[] args) {
System.out.println(factorial(20000));
}
public static BigInteger factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException();
}
synchronized (lock) {
int r = cache.size();
if (n < r) {
return cache.get(n);
}
BigInteger current = cache.get(r-1);
for (;;) {
current = BigInteger.valueOf(r).multiply(current);
cache.add(current);
if (n == r) {
return current;
}
++r;
}
}
}
}
You can resize the Java default stack size runtime with the -Xss switch
eg: java -Xss2048k YourClass
I'm trying to use a priority queue in my code, and for some reason when I remove the objects, they aren't in order. Do you know what i"m doing wrong?
Here's my code:
the contructor:
recordedsong = new PriorityQueue<recordedNote>(50, new Comparator<recordedNote>()
{
public int compare(recordedNote n1, recordedNote n2)
{
long l = n1.rt()-n2.rt();
int i = (int)l;
return i;
}
});
where each recordedNotehas a long value that is returned my the method rt().
But when I call
while (!Song.isEmpty())
{
recordedNote temp = (recordedNote)Song.remove();
and then print temp.rt() for each one, all the numbers are out of order. And not just like reverse order, but all over the place, like 1103, 0, 500, 0, 220 orders like that.
Can you see if there's anything wrong with my contructor?
Thanks!
remove should work, and in fact it does work fine in a small example program that I created to help answer this question:
import java.util.Comparator;
import java.util.PriorityQueue;
public class TestPriorityQueue {
public static void main(String[] args) {
long[] noteTimes = {1103L, 0L, 500L, 0L, 220L, 1021212812012L};
PriorityQueue<RecordedNote> noteQueue = new PriorityQueue<RecordedNote>(10,
new Comparator<RecordedNote>() {
#Override
public int compare(RecordedNote o1, RecordedNote o2) {
Long time1 = o1.getTime();
Long time2 = o2.getTime();
// uses Long's built in compareTo method, so we
//don't have to worry as much about edge cases.
return time1.compareTo(time2);
}
});
for (int i = 0; i < noteTimes.length; i++) {
RecordedNote note = new RecordedNote(noteTimes[i]);
System.out.println(note);
noteQueue.add(note);
}
System.out.println();
while (noteQueue.size() > 0) {
System.out.println(noteQueue.remove());
}
}
}
class RecordedNote {
private long time;
public RecordedNote(long time) {
this.time = time;
}
public long getTime() {
return time;
}
#Override
public String toString() {
return "[Time: " + time + "]";
}
}
So this begs the question, why isn't it working for you? Myself, I don't see enough coherent code in your question to be able to answer this. We're not sure what is Song as I don't see this declared as a class or a variable, and I also don't see where you're using your PriorityQueue variable, recordedsong, anywhere. So I suggest you do the same thing as I: create a small compilable runnable program that we can run and modify and that demonstrates your problem, an http://sscce.org
I guess there is a possibility for i getting 0. So modify compare method so that it returns a positive value rather than the result.
Reading the API docs for PriorityQueue, it states the following:
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).
My guess is that remove() is not obligated to follow the natural ordering, either.