I'm creating a program that creates an array of objects in random positions in an array size 8. Once created, I need them to sort so that all the objects in the array are shifted up to the top, so no gaps exist between them. I'm almost there, but I cannot seem to get them to swap to index 0 in the array, and they instead swap to index 1. Any suggestions? (Must be done the way I'm doing it, not with other sorting algorithms or whatnot)
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
struct WordCount {
string name = "";
int count = 0;
};
int main() {
cout << "Original random array: " << endl;
srand(static_cast<int>(time(0)));
int i = 0;
WordCount wordArr[8];
while (i < 4) {
int randomNum = 0 + (rand() % static_cast<int>(7 + 1));
if(wordArr[randomNum].name == "") {
wordArr[randomNum].name = "word" + static_cast<char>(i);
wordArr[randomNum].count = i;
i++;
}
}
int j = 0;
while (j < 8) {
cout << wordArr[j].name << " " << wordArr[j].count << endl;
j++;
}
cout << "\n\nSorted array: " << endl;
for (int i = 7; i >= 0; i--) {
for (int j = 0; j <= 7; j++) {
if (wordArr[i].name != "") {
if (wordArr[j].name == "") {
WordCount temp = wordArr[i];
wordArr[i] = wordArr[j];
wordArr[j] = temp;
}
}
}
}
int k = 0;
while (k < 8) {
cout << wordArr[k].name << " " << wordArr[k].count << endl;
k++;
}
return 0;
}
If I understand your requirement correctly, you want to move all the non-blank entries to the start of the array. To do this, you need an algorithm like this for example:
for i = 0 to 7
if wordArr[i].name is blank
for j = i + 1 to 7
if wordArr[j].name is not blank
swap [i] and [j]
break
So, starting from the beginning, if we encounter a blank entry, we look forward for the next non-blank entry. If we find such an entry, we swap the blank and non-blank entry, then break to loop again looking for the next blank entry.
Note, this isn't the most efficient of solutions, but it will get you started.
Note also I'd replace the 4 and 8 with definitions like:
#define MAX_ENTRIES (8)
#define TO_GENERATE_ENTRIES (4)
Finally:
wordArr[randomNum].name = "word" + static_cast<char>(i);
That will not do what you want it to do; try:
wordArr[randomNum].name = "word" + static_cast<char>('0' + i);
To append the digits, not the byte codes, to the end of the number. Or perhaps, if you have C++11:
wordArr[randomNum].name = "word" + std::to_string(i);
I see couple of problems.
The expression "word" + static_cast<char>(i); doesn't do what you are hoping to do.
It is equivalent to:
char const* w = "word";
char const* p = w + i;
When i is 2, p will be "rd". You need to use std::string("word") + std::to_string(i).
The logic for moving objects with the non-empty names to objects with empty names did not make sense to me. It obviously does not work for you. The following updated version works for me:
for (int i = 0; i <= 7; ++i) {
// If the name of the object at wordArr[i] is not empty, move on to the
// next item in the array. If it is empty, copy the next object that
// has a non-empty name.
if ( wordArr[i].name == "") {
// Start comparing from the object at wordArr[i+1]. There
// is no need to start at wordArr[i]. We know that it is empty.
for (int j = i+1; j <= 7; ++j) {
if (wordArr[j].name != "") {
WordCount temp = wordArr[i];
wordArr[i] = wordArr[j];
wordArr[j] = temp;
}
}
}
}
There was two problems as :
wordArr[randomNum].name = "word" + static_cast<char>(i); this is not what your are looking for, if you want that your names generate correctly you need something like this :
wordArr[randomNum].name = "word " + std::to_string(i);
Your sorting loop does not do what you want, it's just check for the "gaps" as you said, you need something like this :
for (int i = 0; i < 8; ++i) {
for (int j = i+1; j < 8; ++j) {
if (wordArr[i].name == "" || (wordArr[i].count < wordArr[j].count)) {
WordCount temp = wordArr[i];
wordArr[i] = wordArr[j];
wordArr[j] = temp;
}
}
}
Your algorithm sorts the array, but then looses the sorting again.
You want to swap elements only when i > j, in order to push elements to the top only. As a result, you need to change this:
if (wordArr[j].name == "")
to this:
if (wordArr[j].name == "" && i > j)
Consider this array example:
0
ord 1
0
0
rd 2
word 0
d 3
0
Your code will sort it to:
d 3
ord 1
word 0
rd 2
0
0
0
0
but when i = 3, it will try to populate the 5th cell, and it will swap it with rd 2, which is not what we want.
This will push rd 2 down, but we don't want that, we want gaps (zeroes) to go to the end of the array, thus we need to swap eleemnts only when they are going to go higher, not lower, which is equivalent to say when i > j.
PS: If you are a beginner skip that part.
You can optimize the inner loop by using one if statement and a break keyword, like this:
for (int j = 0; j <= 7; j++) {
if (wordArr[i].name != "" && wordArr[j].name == "" && i > j) {
WordCount temp = wordArr[i];
wordArr[i] = wordArr[j];
wordArr[j] = temp;
break;
}
}
Related
I'm trying to display the elements in an array that sum up to a max number and no two elements are consecutive(adjacent).
I figured out how to calculate the max sum by maintaining an inclusive and exclusive sum of the array elements. Is there any optimized way to capture all the elements that constitute the max sum and display it in reverse order
Code :
int i_sum = tickets[0];
int e_sum = 0;
int new_sum = 0
int sum = 0;
for (int i = 1; i < n; i++)
{
new_sum = (i_sum > e_sum) ? i_sum : e_sum;
i_sum = e_sum + tickets[i];
e_sum = new_sum;
}
(i_sum >= e_sum) ? std::cout << "incl " << i_sum : std::cout << "excl " << e_sum;
For example :
n = 8
array = [ 100 , -3 , 200 , 50 , 400 , -7 , 20 , 80 ]
max sum = 780
output :
80,400,200,100
And if both the inclusive and exclusive sum is alike the output would be the one with the greater element set.
Case :
n = 4
array = [4 , 5 , 4, 3]
max sum = 8
output : 4, 4
Should I maintain two different arrays to hold all the possible values, or insert them one at a time on each pass?
Thanks in advance.
Yes, you could maintain two arrays and copy and swap them at each step. However, that is not optimal. It will make your algorithm O(n2).
std::vector<int> incl, excl;
if (tickets[0] > 0)
incl.push_back(tickets[0]);
for (int i = 1; i < n; i++)
{
std::vector<int> temp;
if (i_sum > e_sum) {
new_sum = i_sum;
} else {
new_sum = e_sum;
temp = excl;
}
i_sum = e_sum + tickets[i];
e_sum = new_sum;
excl.push_back(tickets[i]);
std::swap(incl, excl);
if (temp.size())
excl = temp;
}
incl or excl will contain your solution depending whichever is larger.
I've made a small optimization using std::swap to use move semantics that avoids copies but when e_sum > i_sum, we can't avoid copying temp to excl.
Instead, formulating the same problem using dynamic programming, you can accomplish this in O(n). The idea is similar. Either you include the current element and add to the solution to max sum of second previous element or you exclude the current element to have the solution for the previous element. Code as follows:
vector <int> dp(n);
vector <int> parent(n, 0);
if (tickets[0] > 0) {
dp[0] = tickets[0];
parent[0] = tickets[0];
}
if (tickets[1] > 0) {
dp[1] = tickets[1];
parent[1] = tickets[1];
}
for (int i = 2; i < n ; i++) {
if (dp[i-1] > tickets[i] + dp[i-2]) {
dp[i] = dp[i-1];
} else {
dp[i] = tickets[i] + dp[i-2];
parent[i] = tickets[i];
}
}
cout << "Max sum: " << dp[n-1] << endl;
for(int i = n - 1; i >= 0;) {
if (parent[i]) {
cout << parent[i] << ' ';
i = i - 2;
} else {
i--;
}
}
parent vector can be utilized to trace back the steps taken for the dynamic programming solution.
As a side note, the solution mentioned in your question is slightly incorrect. If the first element is negative, you'd get an unoptimal result.
I've been recently working on a project which includes a Rubik's Cube scramble generator. Basically the program should generate and display random cube notations so that the user can follow each move and have a fairly scrambled cube. Notations include "R" for turning the right layer , "L" for turning the left layer, "F" for turning front layer, "D" for down, "U" for up and "B" for back. And so you have a total of 6 sides "R, L, U, D, F, B". The appostrophe after any of these notations means moving that layer counter clockwise and "2" means moving that layer twice. The problem is you can't have the same notation be repeated next to each other like "R, R" as it would be the same as "R2", nor you can have "R, R' " next to each other as they would cancel each other out. My solution to this was making a 2 dimensional array for storing the 3 groups of notations for every type.
string notation_group[row][column] = { { "R ", "L ", "F ", "B ", "U ", "D " },
{"R' ", "L' ", "F' ", "B' ", "U' ", "D' "}, { "R2", "L2", "F2", "B2", "U2", "D2"} };
This means that whenever the program picks a random column from any of these groups, the program has to prevent the next generated notation from choosing the same column in any other group. So let's say if the program picks the first element of the first group "R", then for the next iteration it can choose any notation except "R", "R' " and "R2", all of which belong to the first column of their respective groups. So all the program has to do is not to pick that column during the next iteration.
I used a "temp" variable to keep in mind the current randomly generated notation and compare it to the next one, and generating a new one whenever those are equal.
int temp;
scrambled_notation[i] = notation_group[pickGroup][pickColumn];
temp = pickColumn;
pickColumn = 0 + rand() % 6;
while (temp == pickColumn) {
pickColumn = 0 + rand() % 6;
}
It does work but there is still another problem, whenever you have something like "R, L" or "R, L', R" be repeated multiple times next to each other they would again cancel each other out leaving no affect on the cube. Is there any idea for how can I prevent two of the opposing sides being repeated next to each other for more than once? I would greatly appreciate the help.
void initScramble(const int, string[][6], string[]);
int main() {
srand(time(0));
const int row = 3, column = 6;
string notation_group[row][column] = { { "R", "L", "F", "B", "U", "D" },
{"R'", "L'", "F'", "B'", "U'", "D'"}, { "R2", "L2", "F2", "B2", "U2", "D2"} };
const int scrambleSize = 22;
string scrambled_notation[scrambleSize];
cout << "SCRAMBLE: " << endl;
initScramble(scrambleSize, notation_group, scrambled_notation);
system("pause");
return 0;
}
void initScramble(const int scrambleSize, string notation_group[][6], string scrambled_notation[]) {
int pickColumn = 0 + rand() % 6;
while (true) {
cin.get();
for (int i = 0; i < scrambleSize; i++) {
int pickGroup = 0 + rand() % 3;
int temp;
scrambled_notation[i] = notation_group[pickGroup][pickColumn];
temp = pickColumn;
pickColumn = 0 + rand() % 6;
while (temp == pickColumn) {
pickColumn = 0 + rand() % 6;
}
}
for (int i = 0; i < scrambleSize; i++) {
cout << scrambled_notation[i] << " ";
}
cin.get();
system("CLS");
}
}
You have to look for the last two moves as long as they are commutative. If not, then you only check for the last move. This is simplified by the fact that each pair of columns are commutative:
void initScramble(const int scrambleSize, string notation_group[][6], string scrambled_notation[]) {
while (true) {
int lastColumn = 7; // Invalid columns
int beforeLastColumn = 7;
cin.get();
for (int i = 0; i < scrambleSize; i++) {
int pickGroup = 0 + rand() % 3;
int pickColumn = 0 + rand() % 6;
bool isCommutative = (lastColumn / 2) == (beforeLastColumn / 2);
while (pickColumn == lastColumn || isCommutative && pickColumn == beforeLastColumn) {
pickColumn = 0 + rand() % 6;
}
scrambled_notation[i] = notation_group[pickGroup][pickColumn];
beforeLastColumn = lastColumn;
lastColumn = pickColumn;
}
for (int i = 0; i < scrambleSize; i++) {
cout << scrambled_notation[i] << " ";
}
cin.get();
system("CLS");
}
}
You don't have to look further since you can have only 2 commutative consecutive moves following your rules of scrambling. For example, 'L,R,L' and 'L,R,R' will be discarded, and thus, 3 commutative moves will never be generated.
First of all, sorry for the mis-worded title. I couldn't imagine a better way to put it.
The problem I'm facing is as follows: In a part of my program, the program counts occurences of different a-zA-Z letters and then tells how many of each letters can be found in an array. The problem, however, is this:
If I have an array that consists of A;A;F;A;D or anything similar, the output will be this:
A - 3
A - 3
F - 1
A - 3
D - 1
But I am required to make it like this:
A - 3
F - 1
D - 1
I could solve the problem easily, however I can't use an additional array to check what values have been already echoed. I know why it happens, but I don't know a way to solve it without using an additional array.
This is the code snippet (the array simply consists of characters, not worthy of adding it to the snippet):
n is the size of array the user is asked to choose at the start of the program (not included in the snippet).
initburts is the current array member ID that is being compared against all other values.
burts is the counter that is being reset after the loop is done checking a letter and moves onto the next one.
do {
for (i = 0; i < n; i++) {
if (array[initburts] == array[i]) {
burts++;
}
}
cout << "\n\n" << array[initburts] << " - " << burts;
initburts++;
burts = 0;
if (initburts == n) {
isDone = true;
}
}
while (isDone == false);
Do your counting first, then loop over your counts printing the results.
std::map<decltype(array[0]), std::size_t> counts;
std::for_each(std::begin(array), std::end(array), [&counts](auto& item){ ++counts[item]; });
std::for_each(std::begin(counts), std::end(counts), [](auto& pair) { std::cout << "\n\n" << pair.first << " - " pair.second; });
for (i = 0; i < n; i++)
{
// first check if we printed this character already;
// this is the case if the same character occurred
// before the current one:
bool isNew = true;
for (j = 0; j < i; j++)
{
// you find out yourself, do you?
// do not forget to break the loop
// in case of having detected an equal value!
}
if(isNew)
{
// well, now we can count...
unsigned int count = 1;
for(int j = i + 1; j < n; ++j)
count += array[j] == array[i];
// appropriate output...
}
}
That would do the trick and retains the array as is, however is an O(n²) algorithm. More efficient (O(n*log(n))) is sorting the array in advance, then you can just iterate over the array once. Of course, original array sequence gets lost then:
std::sort(array, array + arrayLength);
auto start = array;
for(auto current = array + 1; current != array + arrayLength; ++current)
{
if(*current != *start)
{
auto char = *start;
auto count = current - start;
// output char and count appropriately
}
}
// now we yet lack the final character:
auto char = *start;
auto count = array + arrayLength - start;
// output char and count appropriately
Pointer arithmetic... Quite likely that your teacher gets suspicious if you just copy this code, but it should give you the necessary hints to make up your own variant (use indices instead of pointers...).
I would do it this way.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string s;
vector<int> capCount(26, 0), smallCount(26, 0);
cout << "Enter the string\n";
cin >> s;
for(int i = 0; i < s.length(); ++i)
{
char c = s.at(i);
if(c >= 'A' && c <= 'Z')
++capCount[(int)c - 65];
if(c >= 'a' && c <= 'z')
++smallCount[(int)c - 97];
}
for(int i = 0; i < 26; ++i)
{
if(capCount[i] > 0)
cout << (char) (i + 65) << ": " << capCount[i] << endl;
if(smallCount[i] > 0)
cout << (char) (i + 97) << ": " << smallCount[i] << endl;
}
}
Note: I have differentiated lower and upper case characters.
Here's is the sample output:
output
*Sorry about my poor English. If there is anything that you don't understand, please tell me so that I can give you more information that 'make sence'.
**This is first time asking question in Stackoverflow. I've searched some rules for asking questions correctly here, but there should be something I missed. I welcome all feedback.
I'm currently solving algorithm problems to improve my skill, and I'm struggling with one question for three days. This question is from https://algospot.com/judge/problem/read/RESTORE , but since this page is in KOREAN, I tried to translate it in English.
Question
If there are 'k' pieces of partial strings given, calculate shortest string that includes all partial strings.
All strings consist only lowercase alphabets.
If there are more than 1 result strings that satisfy all conditions with same length, choose any string.
Input
In the first line of input, number of test case 'C'(C<=50) is given.
For each test case, number of partial string 'k'(1<=k<=15) is given in the first line, and in next k lines partial strings are given.
Length of partial string is between 1 to 40.
Output
For each testcase, print shortest string that includes all partial strings.
Sample Input
3
3
geo
oji
jing
2
world
hello
3
abrac
cadabra
dabr
Sample Output
geojing
helloworld
cadabrac
And here is my code. My code seems to work perfect with Sample Inputs, and when I made test inputs for my own and tested, everything worked fine. But when I submit this code, they say my code is 'wrong'.
Please tell me what is wrong with my code. You don't need to tell me whole fixed code, I just need sample inputs that causes error with my code. Added code description to make my code easier to understand.
Code Description
Saved all input partial strings in vector 'stringParts'.
Saved current shortest string result in global variable 'answer'.
Used 'cache' array for memoization - to skip repeated function call.
Algorithm I designed to solve this problem is divided into two function -
restore() & eraseOverlapped().
restore() function calculates shortest string that includes all partial strings in 'stringParts'.
Result of resotre() is saved in 'answer'.
For restore(), there are three parameters - 'curString', 'selected' and 'last'.
'curString' stands for currently selected and overlapped string result.
'selected' stands for currently selected elements of 'stringParts'. Used bitmask to make my algorithm concise.
'last' stands for last selected element of 'stringParts' for making 'curString'.
eraseOverlapped() function does preprocessing - it deletes elements of 'stringParts' that can be completly included to other elements before executing restore().
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#define MAX 15
using namespace std;
int k;
string answer; // save shortest result string
vector<string> stringParts;
bool cache[MAX + 1][(1 << MAX) + 1]; //[last selected string][set of selected strings in Bitmask]
void restore(string curString, int selected=0, int last=0) {
//base case 1
if (selected == (1 << k) - 1) {
if (answer.empty() || curString.length() < answer.length())
answer = curString;
return;
}
//base case 2 - memoization
bool& ret = cache[last][selected];
if (ret != false) return;
for (int next = 0; next < k; next++) {
string checkStr = stringParts[next];
if (selected & (1 << next)) continue;
if (curString.empty())
restore(checkStr, selected + (1 << next), next + 1);
else {
int check = false;
//count max overlapping area of two strings and overlap two strings.
for (int i = (checkStr.length() > curString.length() ? curString.length() : checkStr.length())
; i > 0; i--) {
if (curString.substr(curString.size()-i, i) == checkStr.substr(0, i)) {
restore(curString + checkStr.substr(i, checkStr.length()-i), selected + (1 << next), next + 1);
check = true;
break;
}
}
if (!check) { // if there aren't any overlapping area
restore(curString + checkStr, selected + (1 << next), next + 1);
}
}
}
ret = true;
}
//check if there are strings that can be completely included by other strings, and delete that string.
void eraseOverlapped() {
//arranging string vector in ascending order of string length
int vectorLen = stringParts.size();
for (int i = 0; i < vectorLen - 1; i++) {
for (int j = i + 1; j < vectorLen; j++) {
if (stringParts[i].length() < stringParts[j].length()) {
string temp = stringParts[i];
stringParts[i] = stringParts[j];
stringParts[j] = temp;
}
}
}
//deleting included strings
vector<string>::iterator iter;
for (int i = 0; i < vectorLen-1; i++) {
for (int j = i + 1; j < vectorLen; j++) {
if (stringParts[i].find(stringParts[j]) != string::npos) {
iter = stringParts.begin() + j;
stringParts.erase(iter);
j--;
vectorLen--;
}
}
}
}
int main(void) {
int C;
cin >> C; // testcase
for (int testCase = 0; testCase < C; testCase++) {
cin >> k; // number of partial strings
memset(cache, false, sizeof(cache)); // initializing cache to false
string inputStr;
for (int i = 0; i < k; i++) {
cin >> inputStr;
stringParts.push_back(inputStr);
}
eraseOverlapped();
k = stringParts.size();
restore("");
cout << answer << endl;
answer.clear();
stringParts.clear();
}
}
After determining which string-parts can be removed from the list since they are contained in other string-parts, one way to model this problem might be as the "taxicab ripoff problem" problem (or Max TSP), where each potential length reduction by overlap is given a positive weight. Considering that the input size in the question is very small, it seems likely that they expect a near brute-force solution, with possibly some heuristic and backtracking or other form of memoization.
Thanks Everyone who tried to help me solve this problem. I actually solved this problem with few changes on my previous algorithm. These are main changes.
In my previous algorithm I saved result of restore() in global variable 'answer' since restore() didn't return anything, but in new algorithm since restore() returns mid-process answer string I no longer need to use 'answer'.
Used string type cache instead of bool type cache. I found out using bool cache for memoization in this algorithm was useless.
Deleted 'curString' parameter from restore(). Since what we only need during recursive call is one previously selected partial string, 'last' can replace role of 'curString'.
CODE
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#define MAX 15
using namespace std;
int k;
vector<string> stringParts;
string cache[MAX + 1][(1 << MAX) + 1];
string restore(int selected = 0, int last = -1) {
if (selected == (1 << k) - 1) {
return stringParts[last];
}
if (last == -1) {
string ret = "";
for (int next = 0; next < k; next++) {
string resultStr = restore(selected + (1 << next), next);
if (ret.empty() || ret.length() > resultStr.length())
ret = resultStr;
}
return ret;
}
string& ret = cache[last][selected];
if (!ret.empty()) {
cout << "cache used in [" << last << "][" << selected << "]" << endl;
return ret;
}
string curString = stringParts[last];
for (int next = 0; next < k; next++) {
if (selected & (1 << next)) continue;
string checkStr = restore(selected + (1 << next), next);
int check = false;
string resultStr;
for (int i = (checkStr.length() > curString.length() ? curString.length() : checkStr.length())
; i > 0; i--) {
if (curString.substr(curString.size() - i, i) == checkStr.substr(0, i)) {
resultStr = curString + checkStr.substr(i, checkStr.length() - i);
check = true;
break;
}
}
if (!check)
resultStr = curString + checkStr;
if (ret.empty() || ret.length() > resultStr.length())
ret = resultStr;
}
return ret;
}
void EraseOverlapped() {
int vectorLen = stringParts.size();
for (int i = 0; i < vectorLen - 1; i++) {
for (int j = i + 1; j < vectorLen; j++) {
if (stringParts[i].length() < stringParts[j].length()) {
string temp = stringParts[i];
stringParts[i] = stringParts[j];
stringParts[j] = temp;
}
}
}
vector<string>::iterator iter;
for (int i = 0; i < vectorLen - 1; i++) {
for (int j = i + 1; j < vectorLen; j++) {
if (stringParts[i].find(stringParts[j]) != string::npos) {
iter = stringParts.begin() + j;
stringParts.erase(iter);
j--;
vectorLen--;
}
}
}
}
int main(void) {
int C;
cin >> C;
for (int testCase = 0; testCase < C; testCase++) {
cin >> k;
for (int i = 0; i < MAX + 1; i++) {
for (int j = 0; j < (1 << MAX) + 1; j++)
cache[i][j] = "";
}
string inputStr;
for (int i = 0; i < k; i++) {
cin >> inputStr;
stringParts.push_back(inputStr);
}
EraseOverlapped();
k = stringParts.size();
string resultStr = restore();
cout << resultStr << endl;
stringParts.clear();
}
}
This algorithm is much slower than the 'ideal' algorithm that the book I'm studying suggests, but it was fast enough to pass this question's time limit.
Here is my homework problem for C++:
The following algorithm is a solution to a problem that uses nested loops to display a diamond pattern. Translate the algorithm below in to a C++ program. Build, run and test the program.
Algorithm Solution:
Start
Declare numRows as constant integer = 7
Declare maxPlus as constant integer = 7
Declare numSpaces as integer
Declare numPluses as integer
Declare row as integer
Declare space as integer
Declare plus as integer
Set row = 1
Repeat while row >= 1 AND row <= numRows
Set numPluses = 2 * row - 1
if(numPluses > maxPlus) then
Set numPluses = 14 - numPluses
endif
Set numSpaces = (maxPlus - numPluses) / 2
Set space = 1
Repeat while space >= 1 AND space <= numSpaces
Display( ' ')
Set space = space + 1
End Repeat
Set plus = 1
Repeat while plus >= 1 AND plus <= numPluses
Display( '*')
Set plus = plus + 1
End Repeat
Set row = row + 1
Display a new line
End Repeat
Stop
My code:
#include <iostream>
using namespace std;
int main() {
const int numRows = 7;
const int maxPlus = 7;
int numSpaces;
int numPluses;
int row;
int space;
int plus;
row = 1;
while((row >=1) && (row <= numRows)){
numPluses = 2 * row - 1;
if(numPluses > maxPlus){
numPluses = 14 - numPluses;
}
numSpaces = (maxPlus - numPluses)/ 2;
space = 1;
while((space >= 1) && (space <= numSpaces)){
cout << " ";
space++;
}
while((plus >= 1) && (plus <= numPluses)){
cout << "*";
plus++;
}
row++;
cout << endl;
}
return 0;
}
My question is why am I not getting the diamond pattern? I feel like I translated the algorithm correctly, but all I get is a bunch of blank space. Did I read the problem wrong or did I code wrong? screenshot of C++ code
Before the last while loop:
Set plus = 1
You missed that in your translation.
The code did not initialize plus.
There's a habit that saves much grief. Never declare a variable without giving it a meaningful initial value at the point of definition. Limit the scope of variables to where they are actually used. When translating pseudo-code, that can mean doing a little bit of re-writing. Diggit.
int main() {
const int numRows = 7;
const int maxPlus = 7;
for (int row = 1; row <= numRows; ++row) {
const int trianglePluses = 2 * row - 1;
const int numPluses = trianglePluses <= maxPlus
? trianglePluses
: 2 * numRows - trianglePluses;
const int numSpaces = (maxPlus - numPluses) / 2;
for(int space=1; space <= numSpaces; ++space) {
cout << " ";
}
for (int plus = 1; plus <= numPluses; ++plus) {
cout << "*";
}
cout << endl;
}
return 0;
}