I want to check whether a string is palindrome [closed] - c++11

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
char s[100];
//char t[100];
int count = 1;
int j=0;
int x,i;
cin >>s;
x=strlen(s);
//cout <<x <<endl;
cout <<s[j] <<endl;
i=x-1;
cout <<s[i] <<endl;
for (int i = x-1; i <= 0; i--)
{
if (s[j] != s[i])
{
count = 0;
}
j++;
}
if ( count )
{
cout <<"YES";
}
else
{
cout <<"NO";
}
return 0;
I Want to whether a given string is palindrome or not. Whats wrong with this code? i am expecting it to print YES if a palindrome is being input and NO if the string is not a palindrome. But it always prints YES. There are no errors.

Your code is never entering that for loop since the condition i = x-1 and i <=0 wont be true well assuming your string is not empty, then there is no need to keep a count variable since as soon as the strings are not matching you can print NO and exit the code.
You can implement it like:
#include <iostream>
using namespace std;
int main() {
char s[100];
int x,i,j=0;
cin >>s;
x=strlen(s);
i = x-1;
cout <<s[0] <<endl;
cout <<s[i] <<endl;
for (int i = x-1; i >= 0; i--)
{
if (s[j] != s[i])
{
cout <<"NO";
return 0;
}
j ++;
}
cout <<"YES";
return 0;
}

Related

C++ vectors Doesnt recognize [i] INSPITE of the code being EXACTLY IDENTICAL to video tutorial [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
be considerate, this is my first post; first foray into C++!
This is the exact frame where I used the code from this video:
https://youtu.be/Cq1h1KPoGBU?t=340
this is what I wrote down:
vector<int> myVector;
myVector.push_back(3);
std::cout << " Vector: ";
for (unsigned int i = 0; i < myVector.size(); i++);
{std::cout << myVector[i] << " "; }
//(this "[i]" claims to be undefined by C++)//
std::cout << "enter variables" << endl;
C++ says that "i" is undefined at the italicized line (where I have an arrow pointed at the concerned line)
Yes, I included
Please help!
The problem is the semicolon at the end of the line
for (unsigned int i = 0; i < myVector.size(); i++); // <-- here
Because of that, the for loops body is considered to be empty. (And the curly braces ({) just open a code block.)
The code should look like this:
vector<int> myVector;
myVector.push_back(3);
std::cout << " Vector: ";
for (unsigned int i = 0; i < myVector.size(); i++) // notice no ; here
{
std::cout << myVector[i] << " ";
}
std::cout << "enter variables" << endl;

Debugging segmentation fault while sorting

I am asking again with details:
https://stackoverflow.com/questions/33265241/reason-of-segmentation-fault-while-sorting?noredirect=1#comment54333476_33265241
What is the problem in this comparator?
inline bool comp(const vector<int>& a,const vector<int>& b){
for(int i=0;i<a.size() and i<b.size();i++){
if(a[i]<b[i])return 1;
if(a[i]>b[i])return 0;
}
return a.size()<=b.size();
}
I am getting segmentation fault while sorting a vector<vector<int> > using this function as comparator method?
EDIT : Sorry for putting the non-detailed question.
here is the problem statement from interviewbit
https://www.interviewbit.com/courses/programming/topics/backtracking/problems/comb/
inline bool comp(const vector<int>& a,const vector<int>& b){
for(int i=0;i<a.size() and i<b.size();i++){
if(a[i]<b[i])return 1;
if(a[i]>b[i])return 0;
}
return a.size()<=b.size();
}
vector<vector<int> > Solution::combinationSum(vector<int> &A, int B) {
std::sort(A.begin(), A.end());
A.erase(
std::unique(A.begin(), A.end()),
A.end());
/// T[i] : tells us if target i can be achieved or not.
bool T[B+1];
fill(T,T+B+1,0);
T[0]=1;
for(int i=1;i<=B;i++){
for(int j=0;j<A.size() and !T[i];j++){
if(i-A[j]>=0 and T[i-A[j]]){
T[i]=1;
}
}
}
/// Final answer is r[B];
vector< vector<int> > r[B+1];
r[0].push_back(vector<int>());
for(int i=1;i<=B;i++){
if(T[i]){
for(int j=0;j<A.size();j++){
if(i-A[j]>=0 and T[i-A[j]]){
for(int k=0; k<r[i-A[j]].size() ;k++){
vector<int> d=r[ i-A[j] ][ k ];
d.push_back(A[j]);
r[i].push_back(d);
}
}
}
}
}
for(int i=0;i<r[B].size();i++){
sort(r[B][i].begin(),r[B][i].end());
}
cerr << "comming here " << endl;
sort(r[B].begin(),r[B].end(),comp);
cerr << "not reaching here " << endl;
if(r[B].size()==0)return r[B];
vector< vector<int> > ans(1,r[B][0]);
for(int i=1;i<r[B].size();i++){
if(!comp(r[B][i],r[B][i-1])){
ans.push_back(r[B][i]);
}
}
return ans;
}
This code was giving seg fault for input
A : [ 10, 14, 4, 8, 19, 10, 5, 7, 20, 11 ]
B : 31
but on my computer I worked fine.
PS : later I realized that std::vector has < operator and > operator defined which sorts all the vectors in lexicographic order.
sort(r[B].begin(),r[B].end());
Now I wonder why's there segfault on interviewbit platform and not my pc.
General question: What is the reason for these segmentation faults due to bad comparison functions.
for any comparison function f, such that f(a,b) and f(b,a) both returns 0, It will lead to segfault in most cases.
To stack overflow : what is the problem with you guys, you don't let my questions stand for a few hours. Please, before putting anything to hold just think that the user may update the question soon with some more information. Let question stay for at least 24 hrs. Some of us sleep at "night". I asked this question because sometimes bad comparators in sorting can segmentation faults.

How to iterate a string using while loop in C++?

number = 100010001111111
for (int i=0; number.length(); i++) {
while number[i] == 1 {
k++;
}
}
I would like to implement a while-loop as a replacement for the for-loop as shown above.
How could I convert this to a while-loop?
Here's a solution for the problem you mentioned in your comment (Problem - 96A)
#include <iostream>
using namespace std;
int main()
{
cout << "Please enter your players situation" << endl;
std::string str;
cin >> str;
std::string::size_type i = 0;
int NumbersofAppearances = 0;
int ConsectiveNumberSequence = 7; //You can change that to whatever sequence you like
bool IsDangerous=false;
while (i < str.size())
{
if(str[i]=='1' )
{
++NumbersofAppearances;
//We need to check if we reached the consecutive number or not and save it on a different bool variable
if(NumbersofAppearances>=ConsectiveNumberSequence)
IsDangerous=true;
}
else
{
NumbersofAppearances=0;
}
++i;
}
//print out the end result
if (IsDangerous)
cout <<"YES , this is dangerous"<< endl;
else
cout <<"No, this is not dangerous"<< endl;
return 0;
}
And here's a link to Coding ground

HackerEarth Challenge-- Deepu and Array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
[ The Challenge is Over ]
Problem:
An Array of positive elements. Deepu Wants to reduce the elements of the array. He calls a function Hit(X) which reduces the all the elements in the array which are greater than X by 1.
he will call this array many times . Print the array after many calls to Hit(X).
Input:
n----- no of elements in array 10^5.
n elements ----- 1<=element<=10^9.
x----- no of calls to Hit(X) x elements----- 1<=element<=10^9.
output:
Print The array after call to Hit(X) x times.
Time limit--5 secs.
My solution gave Time Limit Exceeded.
My approach:
keep an Original Array
Create a vector of pairs of array elements and their index in the array Sort the vector elements [ ascending ].
Do LowerBound() of C++ STL to get the position of element in the
vector where elements are equal to give element x.
From this element
decrease the elements which are greater than x by 1 till end in the
original array from the index in the pair.
Repeat step 3 & 4 for
every x.
Print the Original array.
I think my solution has complexity n^2.
Can someone Give me an Optimized solution
Thanks
My Code
#define _CRT_DISABLE_PERFCRIT_LOCKS
// lower_bound/upper_bound example
#include <iostream> // std::cout
#include <algorithm> // std::lower_bound, std::upper_bound, std::sort
#include <vector> // std::vector
#include <utility>
using namespace std;
bool pairCompare(const std::pair<long long int, unsigned int>& firstElem, const std::pair<long long int, unsigned int>& secondElem) {
return firstElem.first < secondElem.first;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
unsigned int n, m;
long long int arr[100000], x,temp;
vector<pair<long long int, unsigned int> > vect(100000);
cin >> n;
for (unsigned int i = 0; i < n; i++)
{
cin >> temp;
arr[i] = temp;
vect[i].first = temp;
vect[i].second = i;
}
sort(vect.begin(), vect.begin() + n, pairCompare);
cin >> m;
vector<pair<long long int, unsigned int> >::iterator low;
while (m--)
{
cin >> x;
low = lower_bound(vect.begin(), vect.begin() + n, make_pair(x,2), pairCompare);
if (low != vect.begin() + n)
{
for (unsigned int i = low - vect.begin(); i < n; i++)
{
if (vect[i].first != x)
{
vect[i].first -= 1;
arr[vect[i].second] -= 1;
}
}
}
}
for (unsigned int i = 0; i < n; i++)
{
cout << arr[i]<<" ";
}
return 0;
}
First sort the input array in non-decreasing order. The input array will remain sorted after each of the update operations is run because we are looking for elements greater than x and decrementing them so the worst that could happen is that some elements become equal to x after the operation: array is still sorted.
You can update a range quickly by using a lazy segment tree update. You have to remember the original positions so that you can print the array at the end.

Sort words based on custom ordering [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
User sets his own ordering, for example:
String s = "bawfedghijklmnopqrstuvcxyz"
And than he enter some words, like:
"aa", "bb","cc","dd"
Now I have to print the letters in the sorted form.
The output should be:
bb, aa, dd, cc
I don't have any clue how to proceed, can anyone help me out the with the way to proceed? Code is not required.
A simple answer:
First, recode them into regular sorting order. Eg. In your case, replace all "b" with "A", "a" with "B" and so on.
Sort it.
Decode according to your mapping. Eg. Replace all "A" with "b" etc
Each letter x has some index k[x] in your string s e.g. b has index 0,
a has index 1, w has index 2 and so on (assuming the string s is 0-based).
So you need to sort your words based on the letter indexes as defined by s and
not based on their 'normal'/'natural' indexes (where a would be 0, and b would be 1,
c would be 2 and so on). So for example based on that ordering defined by s you
have that: b < a (as b is mapped to 0 and a is mapped to 1).
That's all this task asks you to do.
To start, take any sorting algorithm (for words), and implement it literally.
Then sorting algorithms have usually a point whey they compare two chars, there
you have to consult the char indexes (as defined by s) and compare based on them.
That's the only change you need to make in the original implementation.
by C
#include <string.h>
#include <ctype.h>
int strcmp_custom(const char *s1, const char *s2){
static const char *table="bawfedghijklmnopqrstuvcxyz";
for ( ; *s1 == *s2; s1++, s2++)
if (*s1 == '\0')
return 0;
if(islower(*s1) && islower(*s2))
return strchr(table, *s1) < strchr(table, *s2) ? -1 : 1;
else
return *(unsigned char *)s1 < *(unsigned char *)s2 ? -1 : 1;
}
int cmp(const void *a, const void *b){
return strcmp_custom(*(const char **)a, *(const char **)b);
}
Just I have tried the following ways ...
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
static Map<String, Integer> map = new HashMap<String, Integer>();
public static int compare(String one, String two) {
int len1 = one.length();
int len2 = two.length();
int n = Math.min(len1, len2);
char v1[] = one.toCharArray();
char v2[] = two.toCharArray();
int i = 0;
int j = 0;
if (i == j) {
int k = i;
int lim = n + i;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return map.get(String.valueOf(c1)) - map.get(String.valueOf(c2));
}
k++;
}
}
return len1 - len2;
}
public static void main(String[] args) {
String FORMAT ="bawfedghijklmnopqrstuvcxyz";
char[] charString = FORMAT.toCharArray();
for(int i=0; i<charString.length; i++){
map.put(String.valueOf(charString[i]), i);
}
List<String> list = Arrays.asList("bw", "bb", "bd", "ba" ); // Input Strings
for(int j=0; j<list.size(); j++){
for(int k=j; k<list.size(); k++){
if(compare(list.get(j),list.get(k)) > 0){
String temp = list.get(j);
list.set(j, list.get(k));
list.set(k, temp);
}
}
}
System.out.println(list);
}
}
Note : If you want add capital letters, numbers and special characters in your input strings You have to add all the characters in FORMAT strings. I hope I will help you some what to go to next level ...

Resources