Palindrome check throws infinite loop (using iterator and linked lists collection) - collections

I´m trying to write a method to determine if a singly linked list of type string is a palindrome.
The idea is to copy the second half to a stack, then use an iterator to pop the elements of the stack and check that they are the same as the elements from 0 to around half of the singly linked list.
But my iterator method is throwing an infinite loop:
public static boolean isPalindrome(LinkedList<String> list, Stack<String> stack ) {
int halfList = (int) Math.ceil(list.size()/2); // we get half the list size, then round up in case it´s odd
// testing: System.out.println("half of size is " + halfList);`
// copy elements of SLL into the stack (push them in) after reaching the midpoint
int count = 0;
boolean isIt = true;
Iterator<String> itr = list.iterator();
Iterator<String> itr2 = list.iterator();
System.out.println("\n i print too! ");
// CHECK!! Node head = list.element();
// LOOP: traverse through SLL and add the second half to the stack (push)
// if even # of elements
if ( list.size() % 1 == 0 ) {
System.out.println("\n me too! ");
while ( itr.hasNext() ) {
String currentString = itr.next(); // this throws an exception in thread empty stack exception
count ++;
if ( count == halfList ) stack.push(list.element());
// THIS IS THE INFINITE LOOP
System.out.println("\n me three! ");
}
}
// else, if odd # of elements
else {
while ( itr.hasNext() ) {
count ++;
if ( count == halfList -1 ) stack.push(list.element());
}
}
// Now we compare the first half of the SLL to the stack (pop off elements)
// even
if ( list.size() % 1 == 0 ) {
while ( itr2.hasNext() ) {
count ++;
if ( count == halfList +1 ) break;
int compared = stack.pop().compareTo(list.element());
if ( compared != 0) isIt = false; // if when comparing the two elements, they aren´t similar, palindrome is false
}
}
// odd
else {
while ( itr2.hasNext() ) {
count ++;
if ( count == halfList ) break;
int compared = stack.pop().compareTo(list.element());
if ( compared != 0) isIt = false;
}
}
return isIt;
}
What am I doing wrong?

There are many issues:
list.size() % 1 == 0 is not checking whether the size is even. The correct check is % 2.
The stack exception cannot occur on the line where you put that comment. It occurs further down the code where you have stack.pop(). The reason for this exception is that you try to pop an element from a stack that has no more elements.
The infinite loop does not occur where you put that comment. It would occur in any of the other loops that you have further in the code: there you never call itr.next() or itr2.next(), and so you'll loop infinitely if you ever get there.
The stack never gets more than 1 value pushed unto it. This is because you have a strict equality condition that is only true once during the iteration. This is not what you want: you want half of the list to end up on the stack. This is also the reason why you get a stack error: the second half of your code expects there to be enough items on the stack.
push(list.element()) is always going to push the first list value to the stack, not the currently iterated one. This should be push(currentString).
count ++; is placed at an unintuitive place in your loops. It makes more sense if that line is moved to become the last statement in the loop.
The if ( count statements are all wrong. If you move count ++ to be the last statement, then this if should read if ( count >= halfList ) for the even case, and if ( count > halfList ) for the odd case. Of course, it would have been easier if halfList would have been adapted, so that you can deal equally with the odd and even case.
The second part of your code has not reset the counter, but continues with count ++. This will make that if ( count == halfList ) is never true, and so this is another reason why the stack.pop() will eventually raise an exception. Either you should reset the counter before you start that second half (with count = 0;) or, better, you should just check whether the stack is empty and then exit the loop.
The second half of your code does not need to make the distinction between odd or even.
Instead of setting isIt to false, it is better to just immediately exit the function with return false, as there is no further benefit to keep on iterating.
The function should not take the stack as an argument: you always want to start with an empty stack, so this should be a local variable, not a parameter.
There is no use in doing Math.ceil on a result that is already an int. Division results in an int when both arguments are int. So to round upwards, add 1 to it before dividing: (list.size()+1) / 2
Avoid code repetition
Most of these problems are evident when you debug your code. It is not so helpful to put print-lines with "I am here". Beter is to print values of your variables, or to step through your code with a good debugger, while inspecting your variables. If you had done that, you would have spotted yourself many of the issues listed above.
Here is a version of your code where the above issues have been resolved:
public static boolean isPalindrome(LinkedList<String> list) {
Stack<String> stack = new Stack<String>();
int halfList = (list.size()+1) / 2; // round upwards
Iterator<String> itr = list.iterator();
while (halfList-- > 0) itr.next(); // skip first half of list
while ( itr.hasNext() ) stack.push(itr.next()); // flush rest unto stack
Iterator<String> itr2 = list.iterator();
while ( itr2.hasNext() && !stack.empty()) { // check that stack is not empty
if (stack.pop().compareTo(itr2.next()) != 0) return false; // no need to continue
}
return true;
}

Related

Why is this code correct while it should clearly run into an infinite loop?

I have been having a problem with this code for a while. The placement of recursive call of the function does not seem right.
i tried running the code and yes it does run into a infinite loop.
// I DEFINE HEAP STRUCTURE AS :
struct heap_array
{
int *array; // heap implementation using arrays(note : heap is atype of a tree).
int capacity; // how much the heap can hold.
int size; //how much size is currently occupied.
void MaxHeapify(struct heap_array *h,int loc) // note : loc is the location of element to be PERCOLATED DOWN.
{
int left,right,max_loc=loc;
left=left_loc_child(h,loc);
right=right_loc_child(h,loc);
if(left !=-1 && h->array[left]>h->array[loc])
{
max_loc=left;
}
if(right!=-1 && h->array[right]>h->array[max_loc])
{
max_loc=right;
}
if(max_loc!=loc) //i.e. if changes were made:
{
//swap the element at max_loc and loc
int temp=h->array[max_loc];
h->array[max_loc]=h->array[loc];
h->array[loc]=temp;
}
MaxHeapify(h,max_loc); // <-- i feel that this recursive call is misplaced. I have seen the exact same code in almost all the online videos and some books i referred to. ALSO I THINK THAT THE CALL SHOULD BE MADE WITHIN THE SCOPE OF condition if(max_loc!=loc).
//if no changes made, end the func right there.
}
In your current implementation, it looks like you don't have a base case for recursion to stop.
Remember that you need a base case in a recursive function (in this case, your MaxHeapify function), and it doesn't look like there is one.
Here is an example of MaxHeap which may be resourceful to look at
// A recursive function to max heapify the given
// subtree. This function assumes that the left and
// right subtrees are already heapified, we only need
// to fix the root.
private void maxHeapify(int pos)
{
if (isLeaf(pos))
return;
if (Heap[pos] < Heap[leftChild(pos)] ||
Heap[pos] < Heap[rightChild(pos)]) {
if (Heap[leftChild(pos)] > Heap[rightChild(pos)]) {
swap(pos, leftChild(pos));
maxHeapify(leftChild(pos));
}
else {
swap(pos, rightChild(pos));
maxHeapify(rightChild(pos));
}
}
}
Here, you can see the basecase of:
if (isLeaf(pos))
return;
You need to add a base case to your recursive function.

Exiting reading two strings with gets in do while loop

I am trying to ask a user to type two strings and then the system makes some action as concatenation.
The program I want to be executed at least once and when the first string is equal to '0' to exit.
Could you please help me do it ?
Because something I make wrong.
#include<stdio.h>
int main()
{
char s1[100],s2[100];
int len = 0;
do
{
len = strlen(s1);
printf("\nString1:");
gets(s1);
printf("String2:");
gets(s2);
} while(s1[0] == '0' && s1[len-1] =='\0');
return 0;
}
Thanks in advance
As per the condition (s1[0] == '0' && s1[len-1] == '\0') the loop will continue only if the first string is '0' and the second string is blank. For all other inputs the loop will exit.
I think your requirement is the condition (s1[0] != '0')

D lang appending to multidimensional dynamic array

I want to append a 2D array to my 3D array. I expect it should be same as int[] arr; arr ~= 3;
void readInput()
{
char[][][] candidate;
char[] buff;
size_t counter = 0;
while ( stdin.readln(buff) )
{
char[][] line = buff.chomp().split();
writeln(line);
candidate ~= line;
writeln(candidate);
if (++counter > 1 ) break;
}
}
And I send the inputs below
201212?4 64
20121235 93
I expect a output like
[["201212?4", "64"], ["20121235", "93"]]
But instead I see
[["20121235", "93"], ["20121235", "93"]]
=~ replaces all the elements in the array with the last added. Where am I doing wrong? How can I meet my expectation?
The problem here is that byLine is reusing buf (that's actually one reason why it asks for a mutable buffer and returns mutable - as a warning that it might change on you).
So when you ~= it, it is really appending the one array multiple times all with a pointer to the same data, so when it changes, that change is seen each time.
You can fix it by adding a .dup to the array you are appending.

Recursive inversion of singly linked list

I've got the following short code, which is a solution to a problem of inverting a linked list.
void backwardslist(atom** head) {
atom* first;
atom* second;
if (*head == NULL) return; //if list is empty
first = *head;
second = first->next; // intuitive
if (second == NULL) return;
backwardslist(&second); // recursive call with 2nd one as head, after we got variables
first and second
first->next->next = first; // when we get to the end, we rearrange it
first->next = NULL; // so last one is pointing to first, first is pointing to NULL
*head = second; // I dont understand this part, so the head is changing from the last,
to the second element as the recursion goes to the beginning or am i
missing something?
}
isn't the second=(pointer to the second of two pointers in the recursion)?
so the first time, i understand, it should point to the last one,
but as the recursion builds back, its constantly changing *head to second.
What's in the second atm that's being used?
Thank you guys
A simple answer that comes to mind is to recursively call your function until the end is reached. Then return the last node. When the recursive function returns, set the next pointer of the node returned to the head node.
1) A->B->C->D
2) A->B->C->D->C
3) A->B->C->D->C->B
4) A->B->C->D->C->B->A
5) D->C->B->A->Null
void recursiveReverse(struct node** head_ref)
{
struct node* first;
struct node* rest;
/* empty list */
if (*head_ref == NULL)
return;
/* suppose first = {1, 2, 3}, rest = {2, 3} */
first = *head_ref;
rest = first->next;
/* List has only one node */
if (rest == NULL)
return;
/* reverse the rest list and put the first element at the end */
recursiveReverse(&rest);
first->next->next = first;
/* tricky step -- see the diagram */
first->next = NULL;
/* fix the head pointer */
*head_ref = rest;
}

Recursive Sudoku Solver- Segmentation Fault (C++)

I'm attempting to make a sudoku solver for the sake of learning to use recursion. I seem to have gotten most of the code to work well together, but when I run the program, I get a windows error telling me that the program has stopped working. A debug indicates a segmentation fault, and I saw elsewhere that this can be caused by too many recursions. I know this is a brute-force method, but again, I'm more worried about getting it to work than speed. What can I do to fix this to a working level?
struct Playing_grid {
//Value of cell
int number;
//wether the number was a clue or not
bool fixed;
}
grid[9][9];
void recursiveTest(int row, int column, int testing)
{
//first, check to make sure it's not fixed
if(grid[row][column].fixed == false)
{
if((checkRow(testing, row) | checkColumn(testing, column) | checkBox(testing,boxNumber(row,column)) | (testing > 9)) == 0)
{
grid[row][column].number = testing;
moveForward(row,column,testing);
recursiveTest(row, column, testing);
}
else if(testing < 9)
{
testing ++;
recursiveTest(row, column, testing);
}
else if(testing == 9)
{
while(testing == 9)
{
moveBack(row,column,testing);
while(grid[row][column].fixed == true)
{
{
moveBack(row,column,test);
}
}
testing = grid[row][column].number;
recursiveTest(row,column,testing);
}
}
}
else
{
moveForward(row,column,testing);
recursiveTest(row,column,testing);
}
}
void moveForward(int& row, int& column, int& test)
{
if(column < 8)
{
column ++;
}
else if((column == 8) & (row != 8))
{
column = 0;
row ++;
}
else if((column == 8) & (row == 8))
{
finishProgram();
}
test = 1;
}
void moveBack(int& row, int& column, int& test)
{
grid[row][column].number = 0;
if(column > 0)
{
column --;
}
else if((column == 0) & (row > -1))
{
column = 8;
row --;
}
else
{
cout << "This puzzle is unsolveable!" << endl;
}
test++;
}
I tried to include all the relevant pieces. I essentially create a 9x9 matrix, and by this point it is filled with 81 values, where empty slots are written as 0. After confirming the test value is valid in the row, column and box, it fills in that value and moves onto the next space. Whenever it runs to 9 and has no possible values, it returns to the previous value and runs through values for that one.
So as to not overwrite known values, the recursive function checks each time that the value of the grid[row][column].fixed is false.
I'd appreciate any insight as to cleaning this up, condensing it, etc. Thanks in advance!
Edit: To exit the recursive loop, when the function is called to move forward, if it has reached the last cell, it completes (saves + outputs) the solution. The code has been adjusted to reflect this.
I'd normally try to fix your code, but I think in this case it's fundamentally flawed and you need to go back to the drawing board.
As a general rule, the pseudocode for a recursive function like this would be
For each possible (immediate) move
Perform that move
Check for win state, if so store/output it and return true.
Call this function. If it returns true then a win state has been found so return true
Otherwise unperform the move
Having tried every move without finding a win state, return false.

Resources