What is the Time Complexity of a PriorityQueue add() and poll() in this case - queue

If I have a PriorityQueue of size 4, and I am iterating over an array of size 'n', and I only want the 4 greatest elements in the array. By the time I reach the end of the array, did this program take O(n) time, or O(nlogn) time. I know PQ add() and remove() take O(logn), but because the PQ size will never be greater than 4, does that mean that this is an O(n) program.
Here is the code if you wish to reference
class Solution {
public int minDifference(int[] nums) {
if(nums.length <= 4) return 0;
PriorityQueue<Integer> maxq = new PriorityQueue();
PriorityQueue<Integer> minq = new PriorityQueue(new Comparator<Integer>(){
public int compare(Integer a, Integer b){
return (a - b) * -1;
}
});
for(int i = 0; i < nums.length; i++){
if(minq.size() < 4){
minq.add(nums[i]);
maxq.add(nums[i]);
}else
{
if(nums[i] > maxq.peek()){
maxq.poll();
maxq.add(nums[i]);
}
if(nums[i] < minq.peek()){
minq.poll();
minq.add(nums[i]);
}
}
}
int smallest4 = minq.poll();
int smallest3 = minq.poll();
int smallest2 = minq.poll();
int smallest = minq.poll();
int biggest4 = maxq.poll();
int biggest3 = maxq.poll();
int biggest2 = maxq.poll();
int biggest = maxq.poll();
int remove3End = biggest4 - smallest;
int remove3Beg = biggest - smallest4;
int twoEnd_oneStart = biggest3 - smallest2;
int oneEnd_twoStart = biggest2 - smallest3;
int a = Math.min(remove3End,remove3Beg);
int b = Math.min(twoEnd_oneStart, oneEnd_twoStart);
return Math.min(a,b);
}
}```

I know PQ add() and remove() take O(logn), but because the PQ size will never be greater than 4, does that mean that this is an O(n) program?
Yes, you are right about that. The n in O(logn) is actually 4, so it becomes O(log4), which is O(1). So you can just say that add() and remove() run in constant time for your case.

Related

How to use selection sort in objects and classes

I'm creating two classes called stop watch and random numbers, which I have already done, but I needed to create a test program that would measure the execution time of sorting 100,000 numbers using selection sort. I know how to create a selection sort, I just don't know how to take the random numbers class and put it together with the selection sort, I get the error message "incompatible types random numbers cannot be converted to int" I hope someone can help me.
My random numbers class
import java.util.Random;
public class randomnumbers {
Random ran1 = new Random();
private int size;
public randomnumbers(){
size = 100000;
}
public int getSize(){
return size;
}
public void setSize(int newSize){
size = newSize;
}
public int [] createArray(int [] size){
for (int i = 0; i < size.length; i++){
size[i] = ran1.nextInt();
}
return size;
}
public static void printArray (int [] array){
for (int i = 0; i < array.length; i++){
if (i < 0){
System.out.println(array[i] + " ");
}
}
}
}
My test Program
public static void main (String [] args){
// Create a StopWatch object
StopWatch timer = new StopWatch();
//create random numbers
randomnumbers numbers = new randomnumbers();
//Create the size of the array
numbers.getSize();
// Invoke the start method in StopWatch class
timer.start();
//sort random numbers
selectionSort();
// Invoke the stop method in StopWatch class
timer.stop();
// Display the execution time
System.out.println("The execution time for sorting 100,000 " +
"numbers using selection sort: " + timer.getElapsedTime() +
" milliseconds");
}
// selectionSort performs a selection sort on an array
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int min = array[i];
int minIndex = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < min) {
min = array[j];
minIndex = j;
}
}
if (i != minIndex) {
array[minIndex] = array[i];
array[i] = min;
}
}
}
}
Where exactly are you getting "incompatible types random numbers cannot be converted to int" error?
There are multiple issues with the code:
Unconventional naming
size field is in randomnumbers class is used as actual array size in constructor but in createArray it's overshadowed with a parameter of the same name but different type and meaning.
You are not passing any array to selectionSort in Main. This is where I get compile error on your code.
printArray has if (i < 0) condition that is false for all ran1.nextInt() numbers so it will not print anything.
Feeding selectionSort with numbers.createArray(new int[numbers.getSize()]) compiles and ends up sorting the array.

Attempts to call a method in the same class not working (java)

I'm creating a random number generator which then sorts the digits from largest to smallest. Initially it worked but then I changed a few things. As far as I'm aware I undid all the changes (ctrl + z) but now I have errors at the points where i try to call the methods. This is probably a very amateur problem but I haven't found an answer. The error i'm met with is "method in class cannot be applied to given types"
Here's my code:
public class RandomMath {
public static void main(String[] args) {
String bigger = bigger(); /*ERROR HERE*/
System.out.println(bigger);
}
//create method for generating random numbers
public static int generator(int n){
Random randomGen = new Random();
//set max int to 10000 as generator works between 0 and n-1
for(int i=0; i<1; i++){
n = randomGen.nextInt(10000);
// exclude 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999, 0000
if((n==1111 || n==2222 || n==3333 || n ==4444 || n==5555)
||(n==6666 || n==7777 || n==8888 || n==9999 || n==0000)){
i--;
}
}
return n;
}
//create method for denoting the bigger number
public static String bigger(int generated){
generated = generator(); /*ERROR HERE*/
System.out.println(generated);
int[] times = new int[10];
while (generated != 0) {
int val = generated % 10;
times[val]++;
generated /= 10;
}
String bigger = "";
for (int i = 9; i >= 0; i--) {
for (int j = 0; j < times[i]; j++) {
bigger += i;
}
}
return bigger;
}
}
You have not defined a method bigger(), only bigger(int generated). Therefore, you must call your bigger method with an integer parameter.

Why am I getting this dynamic IndexOutOfBounds Exception?

I am trying to write a program where text is translated into hexadecimal, then into decimal, and then into an (R, G, B) format. However, when trying to incorporate ClickableRectangle, I get an ArrayIndexOutOfBounds exception that changes dynamically with the sign of rects.
Any thoughts on my problem/optimization?
char[] colors; //Array of characters to be translated into hexadecimal
String r = ""; //Red value of color
String g = ""; //Green value of color
String b = ""; //Blue value of color
int x = 0; //X-coordinate of rectangle
int y = 0; //Y-coordinate of rectangle
int q; //Character count
ClickableRectangle[] rects = new ClickableRectangle[400*400]; //Rectangles
void settings() {
size(displayWidth, displayHeight);
}
void setup() {
background(0);
colors = new char[3];
String s = ([INSERT TRANSCRIPT HERE]); //Too long to be in post//
for (int i = 0; i < s.length(); i+=3) {
for (int j = i; j < i+3; j++) {
colors[j-i] = s.charAt(j);
}
r = hex(colors[0], 2);
g = hex(colors[1], 2);
b = hex(colors[2], 2);
drawAPoint(r, g, b, i);
println(i);
q++;
}
save("SlachtochtFeuf.png"); //Ignore this, using for testing purposes
println("q = " + q);
println("x = " + x);
println("y = " + y);
}
void draw() {
for (int i = 0; i < rects.length; i++) {
if (rects[i].isClicked()) {
println(rects[i].getValue()); //Prints char representation of color
}
}
}
void drawAPoint(String r2, String g2, String b2, int i) {
noStroke();
fill(unhex(r2), unhex(g2), unhex(b2));
rects[i] = new ClickableRectangle(x, y, r2, g2, b2);
rects[i].display();
if (x >= width) {
x = 0;
y += 6;
} else {
x+=6;
}
}
class ClickableRectangle {
int x = 0;
int y = 0;
String r = "";
String g = "";
String b = "";
public ClickableRectangle(int x, int y, String r, String g, String b) {
this.x = x;
this.y = y;
this.r = r;
this.g = g;
this.b = b;
}
public void display() {
fill(unhex(r), unhex(g), unhex(b));
rect(x, y, 6, 6);
}
public void setRGB(String r, String g, String b) {
this.r = r;
this.g = g;
this.b = b;
}
public String getValue() {
return ""+char(unhex(r))+char(unhex(g))+char(unhex(b));
}
public boolean isClicked() {
return mouseX > x && mouseY > y && mouseX < x+6 && mouseY < y+6;
}
}
For future reference, you should tell us exactly which line throws the exception, and you should include all of the code needed to repeat the problem. If the text is too long to post, then narrow it down to a smaller MCVE.
But judging from what I can see, the problem appears to be here:
String s = "test";
for (int i = 0; i < s.length(); i+=3) {
for (int j = i; j < i+3; j++) {
colors[j-i] = s.charAt(j);
}
//other stuff
}
Just run through this in your head:
When i=0 and j=0, you access charAt 0.
When i=0 and j=1, you access charAt 1.
When i=0 and j=2, you access charAt 2.
When i=3 and j=3, you access charAt 3.
When i=3 and j=4, you access charAt 4.
You could also use println() statements to better see what's going on:
for (int i = 0; i < s.length(); i+=3) {
println("i: " + i);
for (int j = i; j < i+3; j++) {
println("j: " + j);
colors[j-i] = s.charAt(j);
}
//other stuff
}
That prints out:
i: 0
j: 0
j: 1
j: 2
0
i: 3
j: 3
j: 4
That last part is the problem- the String I'm using is "test", so it only has 4 characters: charAt(0), charAt(1), charAt(2), and charAt(3). So when you try to access charAt(4), it throws a StringIndexOutOfBoundsException!
I don't know exactly what you're trying to do here, but you'll have to rework your code so that it doesn't try to access characters outside the bounds of the String.
As a side note: it looks like you're trying to code your whole project all at once. Don't do that. Instead, develop this in small increments- try to get smaller pieces working by themselves before you combine them into your whole project. Can you write a separate sketch that simply loops over a String and prints out the characters you're trying to extract? Then if you get stuck, you can use that smaller sketch as your MCVE, and it'll be easier for us to help you.

issue in my if statement to make comparison in my java program

any help please, so i already wrote the prog but my if statement in my for loop is not working. the prog need to generate 6 random nos,then apply bubble sort which i already did.then the user must enter 6 numbers and these numbers must be compared against the random numbers and must say whether numbers are found in the random numbers or not. here's the code. something is wrong with the if statement ` public static void main(String[] args) {
try {
int numbers[] = new int[6]; //random numbers will be stored in new array
//2 loop will be created to avoid duplication of numbers
System.out.println("Array before Bubble sort");
for (int i = 0; i < 6; i++) {
numbers[i] = (int) (Math.random() * 40);
if (i > 0) {
for (int b = 0; b < i; b++) { //
if (numbers[b] == numbers[i]) {
i--; //decrement to continue the for loop if the integer has been repeated
}
}
}
System.out.print(numbers[i] + ","); //random numbers will be printed before using sorting bubble sort
}
//sort an array using bubble sort
bubbleSort(numbers);
System.out.println(" \nArray after bubble sort");
for (int i = 0; i < 6; i++) {
System.out.print(numbers[i] + ",");
}
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\ninput 6 number between 1 and 40");
int inputNumber = Integer.parseInt(input.readLine());
for (int b = 0; b < 6; b++) {
System.out.println("number:");
int outcome=Integer.parseInt(input.readLine());
if(outcome==numbers){
System.out.println("found in random numbers");
}else{
System.out.println("not found in random numbers");
}
}
} catch (Exception e) {
System.out.println("error");
}
}
public static void bubbleSort(int[] numbers) {
int n = numbers.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (numbers[j - 1] > numbers[j]) { //swap the element
temp = numbers[j - 1];
numbers[j - 1] = numbers[j];
numbers[j] = temp;
}
}
}
}
}`
System.out.println("\ninput 6 number between 1 and 40");
//Scanner is specifically designed for getting an input purpose and introduced in Java 5,so better use it
Scanner s = new Scanner(System.in);
//you need to have nested loop here
//But the best way to search is use binary search,as you have already sorted the array
while (s.hasNextInt()) {
//one at a time from the input is put to outcome
int outcome = s.nextInt();
boolean found = false;
for (int b = 0; b < 6; b++) {
found = false;
if (outcome == numbers[b]) {
found = true;
//remember to break the inner loop if a match is found
break;
} else {
found = false;
}
}
if (found == true) {
System.out.println("found in random numbers");
} else {
System.out.println("not found in random numbers");
}

Fibonacci Sequence error

I am coding a Fibonacci sequence in Eclipse and this is my code-
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public int increment() {
int temp = b;
b = a + b;
a = temp;
return value;
}
public int getValue() {
return b;
}
}
It is showing an error in the return value; line saying value cannot be resolved to a variable. I don't see any other errors.
Where is value defined? You return something that was not defined anywhere.
You don't have a "value" defined, this is your error. I don't remember the thing exactly, but I think you don't need a and b, I found this in my code archive, hope it helps.
public class Fibonacci
{
public static long fibo(int n)
{
if (n <= 1) return n;
else return fibo(n - 1) + fibo(n - 2);
}
public static void main() {
int count = 5; // change accordingly, bind to input etc.
int N = Integer.parseInt(count);
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fibo(i));
}
}
In case you want to stay with your own code, try returning "b" as value.
Your method is returning an int variable so you would have to define and return value as an int
I am not sure what you trying to do.
If you have "getValue" method I think "increment" method should be void.
When you want current Fibonacci value use "getValue" method.
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public void increment() {
int temp = b;
b = a + b;
a = temp;
}
public int getValue() {
return b;
}