public BigDecimal next() {
for (int i = 1; i < 100; i++) {
BigDecimal cur = new BigDecimal(1);
BigDecimal prev = new BigDecimal(0);
final BigDecimal next = cur.add(prev);
prev = cur;
cur = next;
}
return cur;
}
Could not implement Bigdecimal in this for loop to get Fibonacci numbers
In your code, hasNext is always false.
This tells the consumer of the iterator that we reached the end of the iteration.
This is what you want to achieve
I replaced all BigDecimal references with Integer. If you want to keep as it then needs to make some small changes.
//This is class with main method
import java.util.Iterator;
public class IteratorPattern {
public static void main(String[] args) {
int n = 10;
FibonacciSequence fibonacciSequence = new FibonacciSequence(n);
System.out.println("iteration using iterator for-loop");
//iteration using iterator for-loop
for (Integer fibonacciNumber : fibonacciSequence) {
System.out.println(fibonacciNumber);
}
System.out.println("iteration using iterator");
//iteration using iterator
Iterator<Integer> iterator = fibonacciSequence.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
class FibonacciSequence implements Iterable<Integer>, Iterator<Integer> {
private final Integer n;
private Integer a;
private Integer b;
private int c = 1;
FibonacciSequence(Integer n) {
this.n = n;
}
#Override
public Iterator<Integer> iterator() {
return new FibonacciSequence(n);
}
#Override
public boolean hasNext() {
return c <= n;
}
#Override
public Integer next() {
c++;
if (a == null && b == null) {
a = 0;
return 0;
} else if (b == null) {
b = 1;
return b;
} else if (a == 0 && b == 1) {
a = 1;
return b;
}
Integer temp = b;
b = b + a;
a = temp;
return b;
}
}
Output :
iteration using iterator for-loop
0
1
1
2
3
5
8
13
21
34
iteration using iterator
0
1
1
2
3
5
8
13
21
34
Now the point is what changes I made.
As told by #Tom S. your hasNext method should return false if the
count reaches to n.
I changed logic in the next method. Take a look at it.
Related
import java.util.Scanner;
class ed {
int fr, r;
int q[];
int n;
ed(int x) {
n = x;
fr = -1;
r = -1;
q = new int[n];
}
void enque(int n) {
int val = n;
while (r < n-1) {
if (r==n-1) {
System.out.println("Overflow");
break;
}
else if (fr==-1 && r==-1) {
fr=0;
r=0;
q[r] = val;
}
else {
r += 1;
q[r] = val;
}
}
}
void deque() {
if (fr==-1 && r==-1) {
System.out.println("Underflow");
}
else if (fr==r) {
fr=-1;
r=-1;
}
else {
fr += 1;
}
}
void reverse(int[] q) {
int a = q[0];
deque();
reverse(q);
enque(a);
}
void printq() {
for (int i = fr; i<=r; i++) {
System.out.print(q[i] + " ");
}
}
}
public class q1 {
static Scanner f = new Scanner (System.in);
public static void main(String[] args) {
int n = f.nextInt();
ed que = new ed(n);
for (int i=0; i<n; i++) {
int x = f.nextInt();
que.enque(x);
}
// que.deque();
// que.printq();
que.reverse(que.q);
}
}
My aim is to reverse a queue (Array) using a recursive function, but in VS Code, the loop is running infinite times and I'm not getting a chance to see the error. I'd like to know my mistake, and any improvement is highly appreciated.
The class ed contains a constructor which initializes the array and the front, rear values. Enque method adds an element to the queue at the rear, deque method removes the front element. Reverse method takes an array input (queue), stores the foremost element in the variable a, deques it, calls itself, then enques it at the back. VS Code is showing the error at line 48 (reverse(q), when it calls itself) but it's not showing the error as it's so far up.
A lot of things are not going the right way in your queue implementation using arrays.
Like, in enque function, you can fill values from rear = 0 to rear = n - 1, because you have n positions available in the q array.
Your code was too long, unstructured, and a bit messy with no proper variable names, So, I didn't read it any further.
But one thing I can make out is that you need to read how to implement a queue using the array.
Now, coming to queue reversal using the recursion part.
Your approach was correct, you just missed out the base case condition.
Steps for reversing queue:
Your queue has some elements, we get the first element out of the queue.
Then, we assume I have a recursive function that reverses the rest of the queue.
In this reversed queue, I just have to push that first element to the back.
And coming to the base case, each time queue size is decreasing by 1, so at the end, the queue will become empty then we don't have to do anything, just return. THUS STOPPING THE RECURSION (which you missed).
Here, is my implementation if you need some reference:
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class Queue {
private int front, rear, capacity;
private int queue[];
Queue(int c) {
front = rear = 0;
capacity = c;
queue = new int[capacity];
}
int size() {
return rear - front;
}
void enqueue(int data) {
if (capacity == rear) {
System.out.printf("Queue is full.\n");
return;
}
else {
queue[rear] = data;
rear++;
}
}
void dequeue() {
if (front == rear) {
System.out.printf("Queue is empty.\n");
return;
}
else {
for (int i = 0; i < rear - 1; i++) {
queue[i] = queue[i + 1];
}
if (rear < capacity)
queue[rear] = 0;
rear--;
}
}
int front() {
if (front == rear) {
System.out.printf("\nQueue is Empty.\n");
return -1;
}
return queue[front];
}
void print() {
int i;
if (front == rear) {
System.out.printf("Queue is Empty.\n");
return;
}
for (i = front; i < rear; i++) {
System.out.printf(" %d, ", queue[i]);
}
System.out.println("");
return;
}
}
class GFG {
static Scanner scanner = new Scanner(System.in);
public static void reverseQueue(Queue queue) {
if (queue.size() == 0) {
return;
}
int frontElement = queue.front();
queue.dequeue();
reverseQueue(queue);
queue.enqueue(frontElement);
}
public static void main (String[] args) {
int queueSize = scanner.nextInt();
Queue queue = new Queue(queueSize);
for (int i = 0; i < queueSize; i++) {
int element = scanner.nextInt();
queue.enqueue(element);
}
queue.print();
reverseQueue(queue);
queue.print();
}
}
You can comment if anything is wrong, or need more clarification.
In the following Main method why isn't the last word (clapping) removed?
public class Main {
public static void main(String[] args) {
HT ht = new HT();
ht.insert("airplane");
ht.insert("distilling");
ht.insert("speaks");
ht.insert("knit");
ht.insert("digitize");
ht.insert("Media");
ht.insert("canonicalized");
ht.insert("libraries");
ht.insert("clapping");
ht.insert("residues");
ht.insert("spoilers");
System.out.println(Arrays.toString(ht.set));
ht.remove("distilling");
ht.remove("knit");
ht.remove("canonicalized");
ht.remove("libraries");
ht.remove("clapping");
System.out.println(Arrays.toString(ht.set));
}
}
The output is
[Media, digitize, airplane, canonicalized, spoilers, distilling, clapping, knit, libraries, speaks, residues]
[Media, digitize, airplane, null, spoilers, null, clapping, null, null, speaks, residues]
clapping is not removed. Why?
HT.java
public class HT {
public String[] set;
public int size;
public HT() {
this.set = new String[11];
this.size = 0;
}
public void insert(String word) {
int hash1 = giveHash1( word );
int hash2 = giveHash2( word );
while (set[hash1] != null) {
hash1 += hash2;
hash1 %= set.length;
}
set[hash1] = word;
size++;
}
public void remove(String word) {
int hash1 = giveHash1(word);
int hash2 = giveHash2(word);
while (set[hash1] != null && !set[hash1].equals(word)) {
hash1 += hash2;
hash1 %= set.length;
}
set[hash1] = null;
size--;
}
public int giveHashCode(String s) {
int hash = 0, x = 31;
for(int i=0;i<s.length();i++) {
hash = x * hash + s.charAt(i);
}
return hash;
}
private int giveHash1(String s) {
return (giveHashCode(s) % set.length < 0)
? (giveHashCode(s) % set.length) + set.length
: giveHashCode(s) % set.length;
}
private int giveHash2(String s) {
return 3 - (((giveHashCode(s) % set.length < 0)
? (giveHashCode(s) % set.length) + set.length
: giveHashCode(s) % set.length) % 3);
}
}
Apart from the modifiers, is there anything wrong with the code? Probably with the hash functions or maybe with insert() or remove()?
The problem is most likely the terminating condition for the loop in the remove() method.
while (set[hash1] != null && !set[hash1].equals(word)) {
which terminates at the first null value it finds.
When inserting, you're updating hash1 if the position is already occupied, so the final position of a word depends on the existing inserted words i.e. the occupied positions.
However when you've already removed a few of the values, the loop in remove() may find empty positions (null values) much sooner, and terminate before actually reaching the position the word was originally inserted in.
public class Linked {
static class Node {
public Node (double item, Node next) { this.item = item; this.next = next; }
public double item;
public Node next;
}
int N;
Node first;
public int posofLastNine () {
if(first != null) {
int index = 0;
int indexTemp = 0;
for (Node x = this.first; x != null; x=x.next) {
if (x.item == 9.0)
indexTemp = index;
index++;
}
index -= 1;
if (this.first.item == 9.0)
return index;
if (indexTemp == 0)
return -1;
return index - indexTemp;
}
return -1;
}
The point is to return the last index in a list that is 9. That is 0,1,9,9,10 would return 3. The issue is, it needs to return -1 if a 9 does not exist. I cannot figure out what's wrong in my code that's preventing it. I cannot add a function or add to parameters. But that's the only issue.
Your code uses variables and classes that you have not shown us, so I can't discern what's going on there. Please provide more information if you want specific help.
To get the last index of a specific element in an array (or list), the easiest way is to simply iterate backwards through the array. Return the first element that matches your parameters. If the whole array is traversed and no dice, return -1.
Here is an example with int[]:
public static int indexOfLastNine(int[] arrayIn) {
for (int i = arrayIn.length - 1; i >= 0; i--) {
if (arrayIn[i] == 9) return i;
}
return -1;
}
Edit
If we have to use your specific type of Linked list, here is an implementation that will work. Please note that this assumes the last node in the Linked list points to null.
public int posOfLastNine() {
int lastNineIndex = -1;
int currentNodeIndex = 0;
Node currentNode = first;
while (true) {
if (currentNode == null) {
break;
}
if (currentNode.item == 9.0) {
lastNineIndex = currentNodeIndex;
}
currentNodeIndex++;
currentNode = currentNode.next;
}
return lastNineIndex;
}
It seems that the logic to detect the last index of 9.0 is overcomplicated.
It could be refactored like this:
remove null check for first
set resulting index to -1 immediately
remove redundant checks after the loop
always return calculated result
public int posofLastNine () {
int result = -1;
int index = 0;
for (Node x = this.first; x != null; x = x.next) {
if (x.item == 9.0) {
result = index;
}
index++;
}
return result;
}
Test code:
public static boolean test(int pos, String data) {
if (null == data || data.trim().isEmpty()) {
return -1 == pos;
}
String[] s = data.split("\\s");
Node head = null;
if (s.length > 0) {
head = new Node(Double.parseDouble(s[0]), null);
Node curr = head;
for (int i = 1; i < s.length; i++) {
Node next = new Node(Double.parseDouble(s[i]), null);
curr.next = next;
curr = next;
}
}
Linked linked = new Linked();
linked.N = pos;
linked.first = head;
return linked.N == linked.posofLastNine();
}
public static void main(String[] args) {
System.out.println(test(-1, null));
System.out.println(test(-1, ""));
System.out.println(test(0, "9 11 14 31"));
System.out.println(test(-1, "8 11 14 31")); // no 9
System.out.println(test(3, "9 11 9 9 14 16"));
}
Output:
true
true
true
true
true
I'm having some trouble with my programming exercise in which I should implement dequeues using arrays.
I already got the operations I need but after the implementation you should run through the numbers 1-20 and insert the even numbers at the end of the dequeue and the odd numbers add the beginning.
After that you should use the method removeFront to remove all numbers in the list and should print them on the console.
There is also the hint that the correct output is: (19,17,15...,1,2,4,...,20).
My problem now is that the number 1 is missing in the list and instead it prints out a null value as the first item to be removed.
public class Dequeues<E> {
private final int max;
private int head;
private int tail;
private E[] deque;
private int counter;
public Dequeues(int max) {
this.max = max;
deque = (E[]) new Object[max];
this.head = 0;
this.tail = 0;
this.counter = 0;
}
public boolean isEmpty (){
return (counter == 0);
}
public boolean isFull() {
return(counter>= max);
}
public void addFront (E x){
if(!isFull()) {
if (head == 0) {
head = deque.length-1;
deque[head] = x;
} else {
deque[head--] = x;
}
counter++;
}
else throw new IndexOutOfBoundsException("Stack is full!");
}
public void addBack(E x){
if(!isFull()) {
if(tail == deque.length-1) {
tail = 0;
deque[tail] = x;
} else {
deque[tail++] = x;
}
counter++;
}
else throw new IndexOutOfBoundsException("Stack is full!");
}
public E removeFront(){
if(!isEmpty()) {
E ret = deque[head];
deque[head++] = null;
if(head >= deque.length) {
head = 0;
}
counter--;
return ret;
}
else throw new IndexOutOfBoundsException("Stack is empty");
}
public E removeBack(){
if (!isEmpty()) {
E ret = deque[tail];
deque[tail--] = null;
if(tail < 0) {
tail = deque.length-1;
}
counter--;
return ret;
}
else throw new IndexOutOfBoundsException("Stack is empty");
}
public static void main (String [] args) {
Dequeues test = new Dequeues(20);
for (int i = 1; i <= test.deque.length; i++) {
if(i % 2 == 0) {
test.addBack(i);
} else if(i % 2 == 1) {
test.addFront(i);
}
}
System.out.println("Use of removeFront and output of the values: ");
for (int i = 0; i < test.deque.length; i++) {
System.out.print(test.removeFront() + " ");
}
}}
Output is the following:
Use of removeFront and output of the values:
null 19 17 15 13 11 9 7 5 3 2 4 6 8 10 12 14 16 18 20
You just simply wrong used -- operator.
Right implementation of the addFront method should be:
public void addFront (E x){
if(!isFull()) {
if (head == 0) {
head = deque.length-1;
deque[head] = x;
} else {
deque[--head] = x;
}
counter++;
}
else throw new IndexOutOfBoundsException("Stack is full!");
}
So, the difference is here deque[--head] = x;
--head means reduce head value by one and then use it.
head-- means use value head and then reduce its value
Your situation was:
head = deque.length-1; head == 19
head != 0 and you go to the else statement. head value = 19. You used head-- and got again 19 and decremented it by one, but had to use --head.
Here is the beginning of my code from my sub class RECORD.
class Record {
private int shares;
private int pricePerShare;
// constructor
Record(int sharesNewValue, int pricePerShareNewValue) {
shares = sharesNewValue;
pricePerShare = pricePerShareNewValue;
}
// inspectors
public int getShares() {
return shares;
}
public int getPricePerShare() {
return pricePerShare;
}
// modifiers
public void setShares(int sharesNewValue) {
shares = sharesNewValue;
}
public void setPricePerShare(int pricePerShareNewValue) {
pricePerShare = pricePerShareNewValue;
}
}
And I want to access the value of shares in my main method that is in a different class.I have the RECORD class linked to another subclass named QUEUE. And in my main method, I have a link to QUEUE with this:
class Lab04a {
public static Queue Q = new Queue();
}
Later on in the code, I need to subtract an int value from the SHARES variable in the Record class, but because that is of type Record, I have no clue how to do this!
I'm not sure if I was clear enough when explaining this, should you have any further questions I'll be more than happy to reply.
Thank you.
Due to my inability to coherently state what I'm trying to accomplish in this lab assignment, I'll just post my other two classes in their entirety:
class Queue {
private int count; // number of elements in the queue
private int head; // index of head element, -1 if queue is empty
private int tail; // index of tail element, -1 if queue is empty
private int MAXSIZE = 1; // Physical size of the queue. DO NOT CHANGE!
private Record[] array; // circular array to store the elements of the queue
// constructor
Queue() {
count = 0;
head = -1;
tail = -1;
array = new Record[MAXSIZE];
}
// inspectors
public boolean empty() {
// Returns true if the queue is empty. Otherwise returns false.
return (count != 0);
}
public int size() {
// Returns the number of elements in the queue
return count;
}
public Record front(){
// Returns the head element of the queue if the queue is not empty.
// Otherwise returns a Record with its data parts set to -1.
if (count == 0)
return new Record(-1, -1);
else
return array[head];
}
public Record rear(){
// Returns the tail element of the queue if the queue is not empty.
// Otherwise returns a Record with its data parts set to -1.
if (count ==0)
return new Record(-1, -1);
else
return array[tail];
}
public String toString() {
// Returns the elements of the queue
String str = "< ";
int h = head;
for (int i = 0; i < count; i++){
str += "(" + array[h].getShares() + ", " + array[h].getPricePerShare() + ") ";
h = (h+1) % MAXSIZE;
}
str += ">";
return str;
}
// modifiers
public boolean dequeue() {
// Removes the head element of the queue.
if (count == 0)
return false;
if (count == 1) {
count = 0;
head = -1;
tail = -1;
}
if (count > 1){
head = (head + 1) % MAXSIZE;
count--;
}
return true;
}
public void enqueue(Record element) {
// Enqueues element to the tail of the queue.
//if max size is reached, it doubles the size to allow for more values
if (count == MAXSIZE) {
Record[] array2 = new Record[MAXSIZE * 2];
for (int i = 0; i < count; i++) {
array2[i] = array[i];
}//closes for loop
array = array2;
MAXSIZE *= 2;
}
tail = (tail + 1) % MAXSIZE;
array[tail] = element;
if (count == 0)
head = tail;
count++;
}//close enqueue method
}//closes class
And then here is my MAIN parent class:
class Lab04a {
public static Queue Q = new Queue(); // creates global object
public static Record R = Record;
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int option, buyPrice, buyShares, sellPrice, sellShares, totalShares, totalValues, totalSellPrice;
option = 0;
totalShares = 0;
totalValues = 0;
Queue Q2 = Q;
while (option != 3) {
System.out.print("Enter option (1:buy, 2:sell, 3:quit): ");
option = scan.nextInt();
if (option == 1) {
System.out.print("Enter shares to buy and price per share: ");
buyShares = scan.nextInt();
buyPrice = scan.nextInt();
Record r = new Record(buyShares, buyPrice);
Q.enqueue(r);
totalShares = totalShares + buyShares;
totalValues = totalValues + (buyShares * buyPrice);
}// ends if
if (option == 2) {
System.out.print("Enter shares to sell and price per share: ");
sellShares = scan.nextInt();
sellPrice = scan.nextInt();
totalSellPrice = sellPrice * sellShares;
if (sellShares > totalShares) {
System.out.println("You do not own enough shares for this sale.");
}
for (int i = sellShares; i > 0; ) {
if (sellShares == Q.front().getShares()) {
i -= Q.front().getShares();
Q.dequeue();
}
if (sellShares < Q.front().getShares()){
Record minus;
minus = Q.front() - sellShares;
Q.front().setShares(minus);
Q.front().setShares(Q.front().getShares());
i -= sellShares;
}
}
}// ends if
// Prints content of Queue
System.out.println("Queue: " + Q.toString());
System.out.println("Total Shares: " + totalShares);
System.out.println("Total Shares Value: $" + totalValues);
System.out.println();
}// ends while loop
System.out.println(Q.toString());
}// ends main method
}
If I understand your question, you can add accessor and mutator methods (or getters and setters)
private int shares;
private int pricePerShare;
public int getShares() {
return shares;
}
public void setShares(int shares) {
this.shares = shares;
}
public int getPricePerShare() {
return pricePerShare;
}
public void setPricePerShare(int pricePerShare) {
this.pricePerShare = pricePerShare;
}
Edit
To use it,
Record record = Q.front(); // <-- I assume your Q contains Record(s).
if (record.getShares() >= sellShares) {
record.setShares(record.getShares() - sellShares); // <-- for example
}
Make sure Q.front() is a method that returns a Record.
If that is true, you should be able to use the line
Q.front().setShares(Q.front().getShares()-MINUS_VALUE))