Java: Having trouble finding the minimum value of a Queue? - java

I'm using arraylist to implement a queue. Everything is going good except when I try to find the minimum value of the queue it does not work properly and the dequeue and peek functions for some reason do not work as expected. I tried going through line by line but I don't understand what is going wrong in the min() function:
public class queuePractice {
static ArrayList<Integer>nums = new ArrayList<Integer>();
static int top = -1;
public static void main(String[] args) {
enqueue(5);
enqueue(2);
enqueue(6);
enqueue(3);
enqueue(12);
enqueue(1);
enqueue(20);
System.out.println("The min is: " + min());
}
public static int peek() {
return nums.get(0);
}
public static void enqueue(int x) {
nums.add(++top, x);
}
public static int dequeue() {
top--;
return nums.remove(0);
}
public static void display() {
for(int x = 0; x <=top; x++) {
System.out.print(nums.get(x) + " ");
}
System.out.println();
}
public static boolean isEmpty() {
return top==-1;
}
public static int min() {
int min = Integer.MAX_VALUE;
while(min > peek()) {
min = peek();
dequeue();
}
return min;
}
}
The peek function keeps returning 2 over and over, even if I change the while loop to a for loop. For some reason it is not updating its value whenever I dequeue it? But going through line by line I can't understand what's wrong.

An easier method would be
List<Integer>nums = Arrays.asList(5,2,35,6); // or use your enqueue
Iterator<Integer> it = nums.iterator();
int min = Integer.MAX_VALUE;
while (it.hasNext()) {
Integer i = it.next();
min = Math.min(i, min);
}
System.out.println(min);
Of course any type of looping around the List would work

Did you mean your code is printing 2 all the time? That's because your min() method always terminate on 2
First iteration your int min value will be 5
Second iteration your int min value will be 2
Third iteration your loop will exit since 2 is not bigger than 6
Then your method will return 2
hope it helps

Related

Finding the Base 2 Logarithm of a number using Recursion in java

I'm trying to write a recursive method in Java to find the base 2 log for multiples of 2.
I've successfully computed the log using this recursive method.
import java.util.*;
class temp
{
static int log(int number)
{
if(number==1)
return 0;
return log(number/2)+1;
}
public static void main(String s[])
{
Scanner input=new Scanner(System.in);
System.out.println("Enter Multiple of 2:");
System.out.println("Log is:"+log(input.nextInt())); //calling log with return value of nextInt()
}
}
Where I've run aground is trying to implement the same program using a different method , a method where i start multiplying from 2 in recursive calls until it becomes equal to the given number. Here's what i've tried:
class logarithmrecursion
{
static int step=1;
static int log(int number)
{
final int temp=number;
if(number>=temp && step!=1)
return 0;
step++;
return log(number*2)+1;
}
}
During the first call, number is equal to temp so i use a step variable to prevent the execution of the termination condition.If i don't use "number" variable in the recursive call, i don't have a way to accumulate the previous product but number variable is already equal to temp and will trigger the termination condition in the next recursive call , thus always giving output 1.
What can i do to make this program work?
The first, reducing, version has a fixed termination value of 1.
But the second version's termination depends on the number, so you have to pass that into the recursive call. So, your main function calls a private recursive version:
static int log(int number) {
return log(number, 1);
}
private static int log(int number, int current) {
return current < number ? log(number, current * 2) + 1 : 0;
}
Note: Your algorithm rounds the value up. To give the (more expected) rounded down result, which agrees with (int)(Math.log(i) / Math.log(2)), use this variation:
private static int log(int number, int current) {
return current <= number / 2 ? log(number, current * 2) + 1 : 0;
}
This kind of pattern - using a wrapper function - is common where initial state of the recursion needs to setup once, but we don't want to burden the caller with having to know about what is an implementation choice.
Your first method may also be coded as one line:
static int log(int number) {
return number == 1 ? 0 log(number/2) + 1;
}
try this:
import java.util.Scanner;
public class LogTest
{
static int calLog(final int number)
{
if(number < 2) {
return 0;
}
return log(number, 2, 1);
}
static int log(final int number, final int accumulated, final int step)
{
if(accumulated >= number) {
return step;
}
return log(number, accumulated * 2, step+1);
}
public static void main(String s[])
{
Scanner input=new Scanner(System.in);
System.out.println("Enter Multiple of 2:");
System.out.println("Log is:"+calLog(input.nextInt())); //calling log with return value of nextInt()
}
}

how to count many times a character occurs in a string without using s loop

the code below is meant to count each time character 'x' occurs in a string but it only counts once ..
I do not want to use a loop.
public class recursionJava
{
public static void main(String args[])
{
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name)
{
int index = 0, result = 0;
if(name.charAt(index) == 'x')
{
result++;
}
else
{
result = result;
}
index++;
if (name.trim().length() != 0)
{
number(name);
}
return result;
}
}
You could do a replacement/removal of the character and then compare the length of the resulting string:
String names = "xxhixx";
int numX = names.length() - names.replace("x", "").length(); // numX == 4
If you don't want to use a loop, you can use recursion:
public static int number (String name)
{
if (name.length () == 0)
return 0;
int count = name.charAt(0)=='x' ? 1 : 0;
return count + number(name.substring(1));
}
As of Java 8 you can use streams:
"xxhixx".chars().filter(c -> ((char)c)=='x').count()
Previous recursive answer (from Eran) is correct, although it has quadratic complexity in new java versions (substring copies string internally). It can be linear one:
public static int number(String names, int position) {
if (position >= names.length()) {
return 0;
}
int count = number(names, position + 1);
if ('x' == names.charAt(position)) {
count++;
}
return count;
}
Your code does not work because of two things:
Every time you're calling your recursive method number(), you're setting your variables index and result back to zero. So, the program will always be stuck on the first letter and also reset the record of the number of x's it has found so far.
Also, name.trim() is pretty much useless here, because this method only removes whitespace characters such as space, tab etc.
You can solve both of these problems by
making index and result global variables and
using index to check whether or not you have reached the end of the String.
So in the end, a slightly modified (and working) Version of your code would look like this:
public class recursionJava {
private static int index = 0;
private static int result = 0;
public static void main(String[] args) {
String names = "xxhixx";
int result = number(names);
System.out.println("number of x: " + result);
}
public static int number (String name){
if(name.charAt(index) == 'x')
result++;
index++;
if(name.length() - index > 0)
number(name);
return result;
}
}
You can use StringUtils.countMatches
StringUtils.countMatches(name, "x");

Stackoverflow error in counting the minimum number of coins to make the sum S

Here I am working on the following problem where we are given n types of coin denominations of values v(1) > v(2) > ... > v(n) (all integers) The following code tries to find the minimum number of coins that are required to make a sum-C. Here the C is 100(see main function).When I run the code, error--"java.lang.StackOverflowError" comes. Please help.
import java.util.ArrayList;
public class Problem2 {
public static int count=4;
public static int []v={25,10,5,1}; //Array storing denominations
private static int findminimum(ArrayList<Integer> v2) {
int count=v2.get(0);
for(int i=0;i<v2.size();i++)
{
if(count>v2.get(i))
{
count=v2.get(i);
}
}
return count;
}
public static int countmincoins(int n)
{
int t;
if(n<0)
{
t=Integer.MAX_VALUE-100 ;
}
if(n==0)
{
t= 0;
}
else
{
ArrayList<Integer> a=new ArrayList<Integer>();
for(int i=0;i<v.length;i++)
{
int temp=0;
temp=countmincoins(n-v[i])+1; //Stackoverflow error
a.add(temp);
}
t=findminimum(a);
}
return t;
}
public static void main(String args[])
{
System.out.println(countmincoins(100));
}
}
If you use recursion then you need to reach a condition to terminate the recursion. But in your code I do not seen any termination logic. Thats why, it get to infinite loop and StackOverflowException. In your code you use following code to terminate.
if(n==0)
{
t= 0;
}
But here n may not be zero. Becuase countmincoins(n-v[i]) do not ensure you to n will be 0.
Your code is infinite cause t will never be <0 or ==0 given that the values in the array and the condition (n - v[i] )+1, v[i] will always return the same value in every call to the method, therefore infinite recursion.
If your not restricted to using recursion the following would be much simpler:
public static int[] denominations = {25,10,5,1};
public static int minimumCoins(int amount){
int total = 0;
for(int denomination: denominations){
while(amount - denomination >= 0){
amount -= denomination;
total++;
}
}
return total;
}
public static void main(String args[])
{
System.out.println(minimumCoins(98));
}

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.

How to multiply the contents of my LinkedList using a while loop and an Iterator

Here is my code:
import java.util.*;
public class Multiply {
public static void main(String[] args) {
LinkedList<Integer>num = new LinkedList<Integer>();
num.add("1");
num.add("2");
num.add("3");
num.add("4");
num.add("5");
product( num );
}
public static void product(LinkedList<Integer> list) {
int index = 0;
Iterator<Integer>productw = list.iterator();
Integer next = productw.next()
while (productw.hasNext()) {
index++;
System.out.println("The product of the numbers is = " + num);
}
}
}
Initially have a multiplication identity ( i.e., 1 ) before your while loop. And keep multiplying to it the iterator values.
Psuedo - code :
public static void product(LinkedList<Integer> list)
{
Iterator<Integer>productw = list.iterator();
int result = 1;
for( int i=0; i<productw.size(); ++i ) {
result *= productw.get(i) ;
}
// result has the answer
}
Edit 1:
The above loop assumes that the list has at least 1 element. If list has no elements, then zero must be the answer which I assume you can easily program it.
You need to define an initial value for the product
And then change it in the loop
Also...Your loop will print the statement multiple times- you don't want that- right ?
HTH

Categories

Resources