String permutation on linking trailing character - string

I'm writing a game for some highschool kids to learn about computer science/math in general.
But I'm also stuck in a question I've designed for myself, and want to see if there's a more efficient way to solve it.
The question:
Give a word "Abc" and a list of words ["Cat", "Tick", "Apple", "Orange", ... ]
Is it possible to construct a word chain in this condition where last character of the first word is same as the first character of any word chosen from the word list. And can this chain be successfully constructed by the given word list? Return true if possible, false otherwise.
INPUT: boolean lastCharPermutation(String startingWord, String [] wordsList) { .. }
OUTPUT: true for able to complete the combination, false otherwise
For example,
Case #1:
Take "Abc", ["Girl", "King", "Cat", "Dog", "Good", "Tick"]
Return true because Abc-Cat-Tick-King-Good-Dog-Girl
Case #2:
Take "Abc", ["Tour", "Game", "Cat", "Bridge", "Women", "Man"]
Return false because Abc-Cat-Tour and stops there

What you want to do is a Eulerian Path..
I had solved the same problem on Codechef.
This is my Code if you wanna use..
Plz tell me if you need a explanation,it is very easy to understand though.
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
int visit[26];
int adj[26][26];
int count=0;
void scc(int i) //Strongly COnnected Component
{
visit[i]=-1;//visiting
for(int t=0;t<26;t++)
{
if(adj[i][t]>0 && visit[t]==0)//not visited yet
scc(t);
}
visit[i]=1;
count++;
}
int main()
{
string in;
int t,n,k,nv,counta,countb,flag;
int a[26],b[26];
cin >> t;
while(t--)
{
cin >> n;
memset(a,0,26*sizeof(int));
memset(b,0,26*sizeof(int));
memset(visit,0,26*sizeof(int));
memset(adj,0,26*26*sizeof(int));
k=26;count=0;counta=0;countb=0;flag=0;nv=0;
while(n > 0)
{
n--;
cin >> in;
a[in[0]-'a']++;
b[in[in.size()-1]-'a']++;
adj[in[0]-'a'][in[in.size()-1]-'a'] = 1;
adj[in[in.size()-1]-'a'][in[0]-'a'] = 1;
}
for(int i=0;i<26;i++)
if(a[i]>0)
{
scc(i);
break;
}
for(int i=0;i<26;i++)
if(a[i]!=0 || b[i]!=0)
nv++;
if(count!=nv)
flag=1;
while(k > 0 && flag!=1 )
{
if(a[k-1]-b[k-1] == 1)
counta++;
else if(b[k-1]-a[k-1] == 1)
countb++;
else if(a[k-1]!=b[k-1])
flag = 1;
k--;
}
if(flag==0 && counta==countb && ( counta==1 || counta ==0))
cout << "Ordering is possible." <<endl;
else
cout << "The door cannot be opened." <<endl;
}
return 0;
}

Related

terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not validAborted

this is my code ,the code is written to calculate all possible codes that can be generated from the given string. using recursion.
if input is 1123 it should print all codes as
aabc
kbc
alc
aaw
kw
#include<bits/stdc++.h>
#include <string.h>
using namespace std;
int getCodes(string input, string output[10000]) {
if(input.size()==0)
{
output[0]="";
return 1;
}
int x=input[0]-'0';
char ch='a'+x-1;
int a=getCodes(input.substr(1),output);
for(int i=0;i<a;i++)
{
output[i]=ch+output[i];
}
int mul=10,x2=0;
for(int i=0;i<2;i++)
{
x2=x2+(input[i]-'0')*mul;
mul=mul/10;
}
string output2[1000]={0};
int b=0;
if(x2>10 && x2<=26)
{
char ch2='a'+x2-1;
b=getCodes(input.substr(2),output2);
for(int i=0;i<b;i++)
{
output[a+i]=ch2+output2[i];
}
}
return a+b;
}
int main(){
string input;
cin >> input;
string output[10000];
int count = getCodes(input, output);
for(int i = 0; i < count && i < 10000; i++)
cout << output[i] << endl;
return 0;
}
i'm trying to solve this problem using recursion where ive devided string into a parts where the single char is handle by code and all other are passed for recursion to take care of in another case first two chars are handled by me and remaining are passed to a recursion and finally all are combined

Complementary DNA(C++)

Task:Write a code to the new string of Dna According to its pattern. Just so you know In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G".
Fore example:DNA_strand ("ATTGC") //returns "TAACG" or DNA_strand ("GTAT") //returns "CATA"
My Code=>
#include <string>
#include <vector>
#include <iostream>
std::string DNAStrand(const std::string& dna)
{
std::string Sym;
std::string c;
std::stringstream s;
s << Sym;
s >> c;
for(int i = 0; i < dna.size() - 1; i++) {
switch (dna[i]) {
case ('A'):
Sym[i] = 'T';
break;
case ('T'):
Sym[i] = 'A';
break;
case ('C'):
Sym[i] = 'G';
break;
case ('G'):
Sym[i] = 'C';
break;
default:
std::cout << "invalid";
} return c.str();
}
int main() {
std::cout << DNAStrand("ATTGC") << "\n"; //retun "TAACG"
std::cout << DNAStrand("GTAT") << "\n"; //retun "CATA"
}
}
You have created a vector<string>, but in the if statements, you are setting the elements of the vector to chars. You want to build a string, not a vector<string>.
You should replace subsequent if statements with else if, or use a switch statement. Otherwise if statements subsequent to a satisfied if statement are executed needlessly.
Replace this vector with an ostringstream. Naming the stream as s, you would append a char named c with s << c. At the end of iterating over dna, return s.str().

My while loop does not work

i want to check the user input which cant larger than 2 and smaller than 1 as well as cant be char (because the input type is int) but my code seem not working.....anyone can help me out? I tried various way but seem i still get it
update: here is part the code , source is declared as int in previous part
Student stu;
List<Student> list;
char id[10];
string str;
int choice;
int source;
bool ask;
while(true){
switch(menu()) {
case 1:
{
system("cls");
if (ReadFile("student.txt", &list)) {
cout << "\nRead File Successfully!\n";
}
else
cout << "\nRead File Failed!\n";
system("pause");
break;
}
case 2:
{
system("cls");
if(list.empty()){
cout<<"\nThe list is empty!\n";
break;
}
cout<<"\nStudent id: ";
getline(cin,str);
while(!isdigit(str)){
cout<<"\nEnter [x] back to menu or re-enter the student id: ";
getline(cin,str);
if(str=="x"||str=="X"){
break;
}
}
strcpy_s(id,10,str.c_str());
if(DeleteRecord(&list, id)){
cout<<"\nStudent successfully deleted!\n";
}
else
cout<<"\nDelete student record failed!\n";
system("pause");
break;
}
case 3:
{
system("cls");
if(list.empty()){
cout<<"\nThe list is empty!\n";
break;
}
cout<<"\nStudent id: ";
getline(cin,str);
while(!isdigit(str)){
cout<<"\nEnter [x] back to menu or re-enter the student id: ";
getline(cin,str);
if(str=="x"||str=="X"){
break;
}
}
strcpy_s(id,10,str.c_str());
if(SearchStudent(&list, id, stu)){
cout<<"\nStudent record found!\n";
}
else
cout<<"\nStudent record not found!\n";
system("pause");
break;
}
case 4:
{
system("cls");
/*if(InsertResult("exam.txt",&list)) //Call InsertResult function
cout<<"*INSERT RESULT SUCCESSFULLY!"<<endl;
else
cout<<"*INSERT RESULT FAILED!"<<endl;
system("pause");
break;
}
case 5:
{
system("cls");
/*if(InsertSubject("subject.txt",&list)) //Call InsertSubject function
cout<<"*INSERT SUBJECT SUCCESSFULLY!"<<endl;
else
cout<<"*INSERT SUBJECT FAILED!"<<endl;*/
system("pause");
break;
}
case 6:
{
system("cls");
cout<<"\nWhere Do You Want To Display The Information?"<<endl;
cout<<"\n1.Screen."<<endl;
cout<<"\n2.File."<<endl;
cout<<endl;
cin>>source;
//check the input
while(!isdigit(source)||source<1||source>2)
{
cout<<"\nPlease Enter A Valid Number Of Source!"<<endl;
cin>>source;
cout<<endl;
}
cout<<"\nWhich Information Do You Want To Display?"<<endl;
cout<<"\n1.Student Information."<<endl;
cout<<"\n2.Student Information & Past Exam Result."<<endl;
cout<<"\n3.Student Information & Current Subject Taken."<<endl;
cout<<"\n4.Student Information & Past Exam Result & Current Subject Taken."<<endl;
cout<<endl;
cin>>choice;
//check the input
if(!isdigit(choice) || choice<1 || choice>2)
{
cout<<"\nPlease Enter A Valid Number Of Choice!"<<endl;
cin>>choice;
cout<<endl;
}
Display(&list,choice,source);
system("pause");
break;
}
case 7:
{
system("cls");
cout << "\nThank You For Using The Program!\n";
system("pause");
return 0;
}
}
}
cout << endl;
system("pause");
}
isdigit expects you to pass a character variable to it. The link I provided has an example:
/* isdigit example */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main ()
{
char str[]="1776ad";
int year;
if (isdigit(str[0]))
{
year = atoi (str);
printf ("The year that followed %d was %d.\n",year,year+1);
}
return 0;
}
You don't need to use isdigit because you are already using a int variable. Thus, this is the code you need:
case 6:
{
system("cls");
cout<<"\nWhere Do You Want To Display The Information?"<<endl;
cout<<"\n1.Screen."<<endl;
cout<<"\n2.File."<<endl;
cout<<endl;
cin>>source;
//check the input
while (source < 1 || source > 2)
{
cout<<"\nPlease Enter A Valid Number Of Source!"<<endl;
cin>>source;
cout<<endl;
}
}
cant larger than 2
source > 2
and smaller than 1
guessing you mean "can't be smaller than 1" source < 1
demo:
#include <iostream>
#include <ctype.h>
using namespace std;
int main(){
char source; // assuming source is char!!
cin>>source;
while(source < '1' || source > '2' || (!isdigit(source)) )
{
cout<<"\nPlease Enter A Valid Number Of Source!"<<endl;
cin>>source;
cout<<endl;
}
return 0;
}
Consider changing the code like this
while(!isdigit(source) || source < '1' || source > '2'))
{
cout<<"\nPlease Enter A Valid Number Of Source!"<<endl;
cin>>source;
cout<<endl;
}
Try this do-while loop Conditions,
do{
cout<<"\nPlease Enter A Valid Number Of Source!"<<endl;
cin>>source;
cout<<endl;
}while(source<1 || source>2 || !isdigit(source));
Edited
char digit; // holds only one char or one digit (0 1 2 3 ...9)
int source;
cin>>digit;
source=digit-'0'; // char to int
do{
cout<<"\nPlease Enter A Valid Number Of Source!"<<endl;
cin>>source;
cout<<endl;
}while(source<1 || source>2 || !isdigit(digit));//digit is character
In isdigit(arg) function,pass char argument its working fine.

Write a snippet of C/C++ code that creates this list of base-12 numbers that count from 0000 to BBBB

Im not sure what to do i want it to print 0000 to ending in BBBB i was trying to use the printf statement anyways, if anyone can help me figure this out that would be great. Thanks
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
char digits[] = "0123456789AB";
for (int column1=0; column1<=12; column1++) {
for (int column2=0; column2<=12; column2++) {
for (int column3=0; column3<=12; column3++) {
for (int column4=0; column4<=12; column4++) {
std::cout<< digits[column2]<<endl;
}
}}}
return(0);
}
The 4 for loops are not the prettiest thing ever, but they should work and I'm not sure it's worth the complications to do it differently. So keep what you have, just print all digits:
std::cout<< digits[column1]<< digits[column2] << digits[column3] << digits[column4]<<endl;
It's better to parametrize the base and the column count to avoid many nested for's.
#include <iostream>
const int columnCount = 4, base = 12;
char digitToChar(int digit) {
if(digit >= 0 && digit <= 9) {
return '0' + digit;
} else {
return 'A' + digit - 10;
}
}
bool increment(int* number) {
int currentColumn = columnCount - 1;
++number[currentColumn];
while(number[currentColumn] == base) {
number[currentColumn] = 0;
--currentColumn;
if(currentColumn < 0) {
return false;
}
++number[currentColumn];
}
return true;
}
void outputNumber(int* number) {
for(int i = 0; i < columnCount; ++i) {
std::cout << digitToChar(number[i]);
}
std::cout << std::endl;
}
int main() {
int number[columnCount] = {0, 0, 0, 0};
bool overflow = false;
do {
outputNumber(number);
overflow = !increment(number);
} while(!overflow);
return 0;
}

Replacing words in c string

I'm having a slight problem with my code here. I just made a small little program to test to put into my actual program. The idea is to replace all the "(star)here(star)" with the string in the add variable. However, when I run the program my final answer is not exactly correct. These are my results:
I_have_a_star_which is super pretty
I_have_a_star_which is super pretty._That_is_great!_I_also_have_a_girlfriendwhich is super pretty
I_have_a_star_which is super pretty._That_is_great!_I_also_have_a_girlfriendwhich is super prett!
Any ideas on what the problem could be would be much appreciated.
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
int main ( )
{
char array[500] = "I_have_a_star_*here*._That_is_great!_I_also_have_a_girlfriend_*here*!",
temp[500],
add[500] = "which is super pretty";
int i=0, j=0;
while(array[i] != '\0')
{
if(array[i] != '*')
{
temp[j]=array[i];
i++;
j++;
}
else
{
strcat(temp,add);
cout << temp << endl;
i+=6;
j+=strlen(add);
}
}
cout << temp << endl;
return 0;
}
The problem is that you're copying characters into the temp array without initializing it or ever NUL terminating it. So when you call strcat or try to print the contents of temp extra garbage on the end may screw things up. Stick memset(temp, 0, sizeof(temp));
before your while loop or change the declaration to temp[500] = "". Alternately, you could add temp[j] = '\0'; just before the call to strcat and just after then loop.
Dude try this...
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
int main ( )
{
char array[500] = "I_have_a_star_*here*._That_is_great!_I_also_have_a_girlfriend_*here*!",
temp[500],
add[500] = "which is super pretty";
int i=0, j=0;
while(array[i] != '\0')
{
if(array[i] != '*')
{
temp[j]=array[i];
i++;
j++;
}
else
{
strcat(temp,add);
i+=6;
j+=strlen(add);
}
}
cout << temp << endl;
return 0;
}

Resources