I've been stuck on this problem that I need to solve for a school assignment a quite a while now, over a week and I still don't have any idea of what to do.
DNA forms the building blocks of our genetic sequence. DNA is made up of two chains of nucleotides. Each nucleotide is one of four possibilities:
A - Adenine
T - Thymine
C - Cytosine
G - Guanine
When combined in the DNA Sequence, A and T can bind and C and G can bind. Other combinations are not valid.
For this assignment, you are going to ask the user for two sequences, then return the number of valid pairs by comparing corresponding positions in the sequence. In other words, you will look at the first character in each. If these are an A & T or a C & G, it s a valid pair. You will then move on to the second pair. You can ignore any invalid characters, but you should not assume that the length of the sequences are equal.
I'm not sure how to go about making a recursion statement that would help this assignment. I'm not sure how I would go about finding the base case for this problem and making a function using recursion that gets back to the base case.
#include "util.h"
using namespace std;
int valid(string first, string second)
{
int valid_pairs;
return valid_pairs;
}
int main()
{
string first;
string second;
cout << "Please enter the first sequence: ";
cin >> first;
cout << "Please enter the second sequence: ";
cin >> second;
cout << "Valid pairs: " << valid(first, second) << endl;
return 0;
}
Recursion is mostly a matter of writing down the possible situations and doing The Right Thing for each one in turn.
In your case, those possibilities are
At least one of the strings is empty (in which case there are no pairs at all)
first[0] and second[0] make a valid pair
first[0] and second[0] don't make a valid pair
Since you know that valid(first.substr(1), second.substr(1)) is going to be the number of valid pairs without the two initial characters, you can now write down the solution.
Doing that left as an exercise.
(First writing the function bool is_valid(char c1, char c2)that determines whether two characters make a valid pair will simplify this function.)
Related
I managed to get this program to work. If the user types an unfixed amount of integers, the program will calculate the average value of it. But I need to end it with <Ctrl-D> in my terminal (end of file) in order for it to work. Why can I not just press enter for it to work?
I also believe that I've used an unnecessary amount of variables. Can it be narrowed down to maybe 2 variables?
#include <iomanip>
#include <iostream>
using namespace std;
int main ()
{
int digit {};
int res {};
int counter {};
cout << "Type in integers: ";
while (cin >> digit)
{
counter ++;
res += digit;
}
cout << "The mean was " << setw(1) << setprecision(1) << fixed << static_cast<double>(res) / static_cast<double>(counter) << endl;
return 0;
}
Why can I not just press enter for it to work?
Because that's not how the overloaded >> formatted extraction operator works. This operator skips over an unlimited amount of whitespace characters, including newline characters, until it reads the integer. It's simply how it works: it will read newlines and spaces, after newlines, and spaces, until it sees a digit. That's its mission in life: read and skip over spaces and newlines until it reads at least one digit. It never gets tired of reading newlines and spaces, and will keep going as long that's the case.
To handle input in the fashion you describe requires a completely different approach: using std::getline to read a single line of input into a std::string, up until the next newline character. Then, once that's done, you can check if the std::string is empty, which means that no input was entered, and then terminate; otherwise take the input in std::string and convert it to an int value (using std::stoi, std::from_chars, or a std::istringstream -- take your pick), and then proceed with the existing algorithm.
Can it be narrowed down to maybe 2 variables?
How do you expect to do that? Hard, immutable logic dictates that you must keep track of at least two discrete values: the total sum and the number of values read. But then you just ran out of variables. You have no more variables to use for storing the next read value (if there is one), using whatever approach you chose to use. So, you can't do it. Rules of logic require the use of at least three variables, possibly more depending on how fancy and robust you want your input validation to work.
This question already has an answer here:
C++ string and string literal comparison
(1 answer)
Closed 1 year ago.
Question - The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word s from Berlandish into Birlandish as t. Help him: find out if he translated the word correctly.
Input -
The first line contains word s, the second line contains word t. The words consist of lowercase Latin letters. The input data do not consist unnecessary spaces. The words are not empty and their lengths do not exceed 100 symbols.
Output -
If the word t is a word s, written reversely, print YES, otherwise print NO.
When I write this code, the output is wrong -
int main(){
char s[100000],a[100000];
cin >> s >> a;
strrev(s);
if(s==a){
cout << "YES";
}else{cout << "NO";}
}
But when I write this code, the output is correct -
int main(){
char s[100000];
string a;
cin >> s >> a;
strrev(s);
if(s==a){
cout << "YES";
}else{cout << "NO";}
}
Why is it like this, is there a rule that a character array cannot be compared to another character array and if so, how can it be compared to a string?
Remember that arrays naturally decay to pointers to their first elements, and it's such pointers that you are comparing.
In short, what you're really doing is:
if(&s[0] == &a[0])
And those two pointers will never be equal.
To compare the contents of character arrays, you need to use strcmp() or similar function instead, eg:
if(strcmp(s, a) == 0)
Since you're programming in C++, please use std::string for all your strings. There are overloads for the == operator that do the right thing if you have std::string values.
Disclaimer: I am super new to c++ and programming in general.
I have a function that takes in a string parameter that is only 2 integers long. I want to use the first and second int of the parameter to index into the chessBoard[8][8] to select a space on the board. Each index (space) in the 2D array (board) contains a char representing a piece type.
The function is supposed to determine the piece type, then call a move function for the specific piece.
Here is a part of the code applied to the king piece.
int movePiece(string startPos) {
string pieceType = chessBoard[startPos[0]][startPos[1]];
cout << chessBoard[startPos[0]][startPos[1]] <<endl;
if (tolower(pieceType) == 'k') {
kingMove(startPos);
}
Line 5 is a test to see what exactly is being returned. For some reason it prints a " " (space) which means it is comparing " " to 'k' or any of the other chars representing piece types. Yet I can put 'cout >> chessBoard[0][3]' and have it print a 'k' (the piece on that space on the board). A space is also returned for any space on the board, not just [0][3].
'startPos' is a string, so I should be able to use startPos[0] and startPos[1] with a stringstream to access the integers, right? What am I doing wrong?
I'm a software engineering student, and i need some help with an assignment i was given
i need a code that corrects a sentence written inside out
example;
i love programming
rp evol i gnimmargo
(what i mean by inside out .... that the sentence gets cut into half and each half is flipped)
i need to correct the scrambled sentence
i already started it by counting the charterers in the string that the user enters and cutting the sentence .... but i just cant figure out how to flip each half then join them
any ideas??
#include <iostream>
#include <string>
using namespace std;
//prototype
int NumberOfChar(string testCase);
int main()
{
// declaration
int N, halfCharNum, halfTestCase, size;
string testCase;
// input
cout<<"please enter an integer number, that will represent the number of test cases: "<<endl;
//cin>>N;
cout<< NumberOfChar(testCase)<<endl;
halfCharNum=size/2;
return 0;
}
int NumberOfChar(string testCase)
{
cout << "Enter your string: " <<endl;
getline(cin,testCase);
const int size=testCase.length();
cout << "The total number of characters entered is: " << endl;
return size;
}
This takes all of two lines of C++ code.
1) reverse the string (std::reverse)
2) Rotate the string left n characters where n is half the number of characters in the string. (std::rotate)
First, replace each element in the string with the element on the other end and work your way in.
i.e. in the string "rp evol i gnimmargo" exchange the first character "r" with the last character "o" and then work your way in, next exchanging "p" with "g" and so on.
That leaves you with "ogramming i love pr"
Then, swap the first and second halves of the string.
i.e. "ogramming i love pr" can be split into "ogramming" and " i love pr" -- just swap them for " i love pr" and "ogramming" and combine them
Just use a large dictionary of english words and implement an evolutionary algorithm. Might not be the shortest path to glory but definitely a fun task :-)
Sample dictionaries (you might need anyway) can be found
here,
here,
or here
This is for homework! But I need help anyway. The assignment is to input a sentence then output the number of words, and the number of occurrences of each letter. The output must have the letters in alphabetical order. So far, I've been able to count the number of words and get all the letters to lower case so that I'll be able to keep count of them. My question is how to actually keep count of the letters.
Example of output:
I say Hi.
3 words
1 a
1 h
2 i
1 s
1 y
Here's the code that I have so far:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
int letters[26];
char letter;
int word = 0;
cout << "Please enter a sentence: "<< endl;
do
{
cin.get(letter);
if(isspace(letter))
word++;
letter = tolower(letter);
cout << letter;
}
while (letter != '\n');
cout << "The number of words = " << word << endl;
return 0;
}
Should I input directly into a C-string? or will that mess up the word count?
If you're allowed to use STL, use std::map for mapping letters to counters. It will additionally sort the letters.
Otherwise, treat chars as indexes in an array of counters and increment them.
My question is how to actually keep
count of the letters
It's fairly straight forward. Simply create an array of 26 integers, (one for each letter), and initialize it to zero.
int letters[26] = { 0 }; // Initialize array to zero
Each value in the array corresponds to a count of a particular letter. Array index 0 refers to 'a', array index 1 refers to 'b', and so on. Then, everytime you encounter a letter, increment the appropriate value in the array. You can use the character 'a' (ASCII value 97) as a starting offset. So, given the variable char letter; you would do:
++letters[tolower(letter) - 'a'];
But always make sure that before you increment the appropriate value in the array, you check that isalpha(letter) && islower(letter) to make sure that your letter is in the range of lowercase a-z; otherwise you will access an index beyond the bounds of the array. You can also test for this condition by saying if (letter >= 'a' && letter <= 'z').
Hint: tolower(letter)-'a' is:
0 if letter is a
1 if letter is b
...
Hm, just few points to make your home task more useful to you (and your code more correct):
Think what happens if you have file with several spaces in a row (word counting).
Think how to be more correct with 'letters' (check for isalpha() at least). Also isalpha() could be key for simpler counting with fixed array [256] (this might be even the best solution as for performance vs std::map usage, check std::map documentation anyway).
Think about more effective file input. At least line at once.