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')
Related
Anyone knows if there are there any method for comparing the two pointers, let's say there are two pointers ptr1 and ptr2, as shown in the picture, how can i perform some operations similar (ptr2 < ptr1) to check whether a specific pointer passed another pointer, for example to check whether ptr2 passed ptr1 such that ptr2 is on the right side while ptr1 is on the left side. Thank you in advance.
Comparing the pointer values themselves will not tell you which node is before the other one in a linked list. For that you will need to step through your linked list.
You could have these pointers traverse the linked list in tandem. The one that reaches the end of the list first is necessarily the one that is coming after the other one.
In pseudo code (c-style):
int compare(node* ptr1, node* ptr2) {
if (ptr1 == ptr2) return 0; // equal
while (ptr1 != NULL && ptr2 != NULL) {
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
return ptr2 == NULL ? -1 : 1;
}
If the list is long, and the pointers are not far from each other, you can gain some time by also checking whether one of the traversing pointers becomes equal to an original pointer. Then you can also take your conclusions:
int compare(node* ptr1, node* ptr2) {
if (ptr1 == ptr2) return 0; // equal
cur1 = ptr1;
cur2 = ptr2;
while (true) {
if (cur2 == NULL || cur1 == ptr2) return -1; // ptr1 before ptr2
if (cur1 == NULL || cur2 == ptr1) return 1; // ptr2 before ptr1
cur1 = cur1->next;
cur2 = cur2->next;
}
}
All this assumes that the given pointers are both pointing to members of the same linked list. With the above function you can now do:
// ...
int res = compare(ptr1, ptr2);
if (res < 0) output("*ptr1 comes before *ptr2");
if (res > 0) output("*ptr1 comes after *ptr2");
if (res == 0) output("*ptr1 is the same as *ptr2");
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;
}
I have a problem with this function I created, the function should return the number of characters entered in the array. but always return 20 that its the limit of the array itself.
Code:
int LongitudCadena (char *pcadena) {
// cantidad its the counter of chars that in the array
int cantidad=0;
//M its a constant equals 20, that its the limit of the array
for(int a=0;a<M;a++){
if(pcadena!=0){
pcadena++;
cantidad++;
} else {
return 0;
}
}
return cantidad;
}
Replace if(pcadena!=0) by if(*pcadena!='\0').
Also, change the else condition to either
else
{
return cantidad;
}
or
else
{
break;
}
pcadena, the pointer, is never going to be 0 (NULL)... what you meant that the character it points to is '\0'
if (*pcadena)
Another problem is once you find the terminator, you return 0. You should return cantidad there.
Note: cantidad == a
There are several problems with the code. First of all, you should test the content of the address the pointer points at.
...
if(*pacadena!=0) {
....
Secondly, why do you return 0 in the while loop when pcadena is 0? Shouldn't you return the current length? Assuming your data always terminate with \0, then your for loop should look something like this:
for(int a=0;a<M;a++){
if(*pcadena){
pcadena++;
cantidad++;
} else {
return cantidad;
}
}
Further, if your data is indeed terminated by \0, then you should just use the strlen function instead. There's no need to rewrite this.
The function gets an integer and a digit, and should return true
if the digit appears an even number of times in the integer, or false if not.
For example:
If digit=1 and num=1125
the function should return true.
If digit=1 and num=1234
the function should return false.
bool isEven(int num, int dig)
{
bool even;
if (num < 10)
even = false;
else
{
even = isEven(num/10,dig);
This is what I've got so far, and I'm stuck...
This is homework so please don't write the answer but hint me and help me get to it by myself.
To set up recursion, you need to figure out two things:
The base case. What is are the easy cases that you can handle outright? For example, can you handle single-digit numbers easily?
The rule(s) that reduce all other cases towards the base case. For example, can you chop off the last digit and somehow transform the solution for the remaning partial number into the solution for the full number?
I can see from your code that you've made some progress on both of these points. However, both are incomplete. For one thing, you are never using the target digit in your code.
The expression num%10 will give you the last digit of a number, which should help.
Your base case is incorrect because a single digit can have an even number of matches (zero is an even number). Your recursive case also needs work because you need to invert the answer for each match.
This funtion isEven() takes a single integer and returns the true if the number of occurence of numberToCheck is even.
You can change the base as well as the numberToCheck which are defined globally.
#include <iostream>
using std::cout;
using std::endl;
// using 10 due to decimal [change it to respective base]
const int base = 10;
const int numberToCheck = 5;
//Checks if the number of occurence of "numberToCheck" are even or odd
bool isEven(int n)
{
if (n == 0)
return 1;
bool hasNumber = false;
int currentDigit = n % base;
n /= base;
if (currentDigit == numberToCheck)
hasNumber = true;
bool flag = isEven(n);
// XOR GATE
return ((!hasNumber) && (flag) || (hasNumber) && (!flag));
};
int main(void)
{
// This is the input to the funtion IsEven()
int n = 51515;
if (isEven(n))
cout << "Even";
else
cout << "Odd";
return 0;
}
Using XOR Logic to integrate all returns
// XOR GATE
return ((!hasNumber) && (flag) || (hasNumber) && (!flag));
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.