Coursera DSA Algorithmic toolbox week 4 2nd question- Partitioning Souvenirs - c++

Problem Statement-
You and two of your friends have just returned back home after visiting various countries. Now you would
like to evenly split all the souvenirs that all three of you bought.
Problem Description
Input Format- The first line contains an integer ... The second line contains integers v1, v2, . . . ,vn separated by spaces.
Constraints- 1 . .. . 20, 1 . .... . 30 for all ...
Output Format- Output 1, if it possible to partition đť‘Ł1, đť‘Ł2, . . . , đť‘Łđť‘› into three subsets with equal sums, and
0 otherwise.
What's Wrong with this solution? I am getting wrong answer when I submit(#12/75) I am solving it using Knapsack without repetition taking SUm/3 as my Weight. I back track my solution to replace them with 0. Test cases run correctly on my PC.
Although I did it using OR logic, taking a boolean array but IDK whats wrong with this one??
Example- 11
17 59 34 57 17 23 67 1 18 2 59
(67 34 17)are replaced with 0s. So that they dont interfare in the next sum of elements (18 1 23 17 59). Coz both of them equal to 118(sum/3) Print 1.
#include <iostream>
#include <vector>
using namespace std;
int partition3(vector<int> &w, int W)
{
int N = w.size();
//using DP to find out the sum/3 that acts as the Weight for a Knapsack problem
vector<vector<int>> arr(N + 1, vector<int>(W + 1));
for (int k = 0; k <= 1; k++)
{
//This loop runs twice coz if 2x I get sum/3 then that ensures that left elements will make up sum/3 too
for (int i = 0; i < N + 1; i++)
{
for (int j = 0; j < W + 1; j++)
{
if (i == 0 || j == 0)
arr[i][j] = 0;
else if (w[i - 1] <= j)
{
arr[i][j] = ((arr[i - 1][j] > (arr[i - 1][j - w[i - 1]] + w[i - 1])) ? arr[i - 1][j] : (arr[i - 1][j - w[i - 1]] + w[i - 1]));
}
else
{
arr[i][j] = arr[i - 1][j];
}
}
}
if (arr[N][W] != W)
return 0;
else
{
//backtrack the elements that make the sum/3 and = them to 0 so that they don't contribute to the next //elements that make sum/3
int res = arr[N][W];
int wt = W;
for (int i = N; i > 0 && res > 0; i--)
{
if (res == arr[i - 1][wt])
continue;
else
{
std::cout << w[i - 1] << " ";
res = res - w[i - 1];
wt = wt - w[i - 1];
w[i - 1] = 0;
}
}
}
}
if (arr[N][W] == W)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
int n;
std::cin >> n;
vector<int> A(n);
int sum = 0;
for (size_t i = 0; i < A.size(); ++i)
{
int k;
std::cin >> k;
A[i] = k;
sum += k;
}
if (sum % 3 == 0)
std::cout << partition3(A, sum / 3) << '\n';
else
std::cout << 0;
}

Sum/3 can be achieved by multiple ways!!!! So backtracking might remove a subset that has an element that should have been a part of some other subset
8 1 6 is 15 as well as 8 2 5 makes 15 so better is u check this
if(partition3(A, sum / 3) == sum / 3 && partition3(A, 2 * (sum / 3)) == 2 * sum / 3 && sum == partition3(A, sum))

Related

Implementation Working in Python But Not in C++

So I made a program that takes in three strings, A, B, and C and determines whether or not C is a merge of A and B. A merge is defined as combination of the letters in A and B such that the ordering of the letters of A and B in relation to one another are preserved. So if A = "ab", B = "ba", and C = "abab", C is a valid merge of A and B since the first and last letters of C can be thought of as "from A" and the middle two from B. This combination of letters preserves their order in A and B and so C is a valid merge.
My program also capitalizes the letters in C that are "from A" meaning it outputs "AbaB".
I'm more comfortable with Python so I wrote out my implementation there first and then translated it to C++. But the really weird thing is that it works perfectly in Python but not in C++. I checked line by line and everything matches up perfectly but it's still giving the wrong output.
So for an example, for the input A == "ab", B = "ba", and C = "abab", my Python implementation correctly outputs "AbaB". But, my C++ implementation outputs "ABba".
The problem only seems to be with this part of the output. The C++ program seems to be able to correctly identify whether or not C is a valid merge of A and B.
Here's my Python program:
def findPath(array, A, B):
output = ""
M = len(A)
N = len(B)
i = M
j = N
while(j > 0):
print(i,j)
if(array[i][j-1]):
output = B[j-1] + output
j -= 1
else:
output = A[i-1].upper() + output
i -= 1
while(i > 0):
output = A[i-1].upper() + output
i -= 1
return output
def isInterleaved(A,B,C):
M = len(A)
N = len(B)
output = ""
array = [[False] * (N + 1) for i in range(M + 1)]
if(M +N != len(C)):
return False
for i in range(M+1):
for j in range(N+1):
if (i== 0 and j == 0):
array[i][j] = True
elif (i == 0):
if (B[j-1] == C[j-1]):
array[i][j] = array[i][j-1]
elif (j == 0):
if (A[i-1] == C[i-1]):
array[i][j] = array[i-1][j]
elif (A[i - 1] == C[i + j - 1] and B[j - 1] != C[i + j - 1]):
array[i][j] = array[i-1][j]
elif (A[i - 1] != C[i + j - 1] and B[j - 1] == C[i + j - 1]):
array[i][j] = array[i][j-1]
elif (A[i - 1] == C[i + j - 1] and B[j - 1] == C[i + j - 1]):
array[i][j] = (array[i - 1][j] or array[i][j - 1])
print(findPath(array, A,B))
return array[M][N]
print(isInterleaved("ab", "ba",
"abab"))
And here's my C++ program:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
bool graph[1001][1001];
bool isInterleaved(string A, string B, string C)
{
int M = A.size();
int N = B.size();
if(M + N != C.size())
{
return false;
}
for (int i = 0; i < M + 1; i++)
{
for(int j = 0; j < N + 1; j++)
{
if (i == 0 and j == 0) { graph[i][j] = true; }
else if(i == 0)
{
if (B[j-1] == C[j-1])
{
graph[i][j] = graph[i][j-1];
}
}
else if(j == 0)
{
if (A[i-1] == C[i-1]) { graph[i][j] = graph[i-1][j];}
}
else if (A[i - 1] == C[i + j - 1] and B[j - 1] != C[i + j - 1])
{
graph[i][j] = graph[i-1][j];
}
else if (A[i - 1] != C[i + j - 1] and B[j - 1] == C[i + j - 1])
{
graph[i][j] = graph[i][j-1];
}
else if (A[i - 1] == C[i + j - 1] and B[j - 1] == C[i + j - 1])
{
graph[i][j] = (graph[i - 1][j] or graph[i][j - 1]);
}
}
}
return graph[M][N];
}
string findPath(string A, string B)
{
string output = "";
int M = A.size();
int N = B.size();
int i = M;
int j = N;
for(int k = 0; k < M; k++)
{
A[k] = toupper(A[k]);
}
while(j > 0)
{
if(graph[i][j-1])
{
output = B[j - 1] + output;
j -= 1;
}
else
{
output = A[i-1]+ output;
i -= 1;
}
}
cout << output << endl;
while(i > 0)
{
output = A[i-1] + output;
i -= 1;
}
return output;
}
int main()
{
string in;
string out;
cout << "Enter the name of input file: ";
cin >> in;
cout << "Enter the name of output file: ";
cin >> out;
ifstream myfile;
myfile.open(in);
ofstream outfile;
outfile.open(out);
string line;
vector<string> arguments;
int count = 0;
while(getline(myfile, line))
{
arguments.push_back(line);
count ++;
if(count == 3)
{
count = 0;
if(isInterleaved(arguments[0], arguments[1], arguments[2]))
{
outfile << findPath(arguments[0], arguments[1]) << "\n";
}
else
{
outfile << "*** NOT A MERGE ***" << "\n";
}
arguments.clear();
}
}
myfile.close();
outfile.close();
return 0;
}
For the C implementation, it takes in a list of test cases so that every block of three lines gives the parameters for a different test case. The first line gives the string A, the second, the string B, and the third, is C. It outputs the results into a text file giving the capitalized-A version of C when it's a valid merge and the string "*** NOT A MERGE ***" when it's not.
Any help with this would be greatly appreciated. I'm pretty sure it has to be something small like a method that's not giving me what I expect it to.
This is not really an answer, but sometimes when things don’t work it’s better to start over from an easily testable MWE. I’d suggest keeping it trivial, without file I/O clutter, focused only on the merger detection and without an arbitrary hard limit of 1000:
#include <iostream>
#include <set>
#include <string_view>
#include <tuple>
int main(int argc, const char *const *argv) {
if (argc != 4) return 3;
const std::string_view a{argv[1]}, b{argv[2]}, c{argv[3]};
const auto report{[a, b, c](bool result) {
std::cout << '\'' << c << "' is " << (result ? "" : "NOT ")
<< "a merger of '" << a << "' and '" << b << "'\n";
}};
std::set<std::tuple<size_t, size_t>> state{{0, 0}};
do {
const auto s{state.begin()};
const auto [pc, pa] = *s;
const size_t pb = pc - pa;
state.erase(s);
if (pc < c.size()) {
if (pa < a.size() && c[pc] == a[pa])
state.emplace_hint(state.end(), pc + 1, pa + 1);
if (pb < b.size() && c[pc] == b[pb])
state.emplace_hint(state.end(), pc + 1, pa);
} else if (pa == a.size() && pb == b.size()) {
report(true);
return 0;
}
} while (!state.empty());
report(false);
return 1;
}
What it does is (indeed) trivial: It records combinations of (position in merger candidate C, position in merger input A [explicit], position in merger input B [implicit]) achieved thus far. Obviously, (0, 0, 0) is a trivially satisfied starting point. Then it keeps trying to advance each already achieved position by one character. Ultimately it either reaches the ends of all of A, B and C at once, at which point C is confirmed to be a merger of A and B, or it exhausts all achieved positions recorded for future consideration, which means that one cannot merge A and B into C in any way.
(Presumably, you need to add an extra piece of data into the state if you want to also report a “merger recipe” together with a positive answer. It could also use an early check whether the string lengths add up.)
Now we can test that a bit (assuming that the binary is called merger):
#!/bin/bash
abc012=(abc012 ab0c12 ab01c2 ab012c a0bc12 a0b1c2 a0b12c a01bc2 a01b2c a012bc
0abc12 0ab1c2 0ab12c 0a1bc2 0a1b2c 0a12bc 01abc2 01ab2c 01a2bc 012abc)
acb012=(acb012 ac0b12 ac01b2 ac012b a0cb12 a0c1b2 a0c12b a01cb2 a01c2b a012cb
0acb12 0ac1b2 0ac12b 0a1cb2 0a1c2b 0a12cb 01acb2 01ac2b 01a2cb 012acb)
for m in "${abc012[#]}"; do
./merger abc 012 "$m" # …is a merger…
done
for m in "${acb012[#]}"; do
./merger abc 012 "$m" # …is NOT a merger…
done

Caesar cipher : how to calculate with shifting value > 10 ( or larger )?

As i know , the " formula " of Caesar Shifting is (x + k ) % 26 , where k is the shifting value and decryption just replace " + " to " - ".
but my code does not work when k > 10 (after i tested k = 10 , i find that the "shift" of the first few characters is wrong, so I estimate that k > 10 will be wrong (the number of incorrect characters increase) as well. ). I first change the characters to ASCII and then do the calculation. Finally change it back to characters.
Here are my code.
#include <iostream>
#include <string>
using namespace std;
int main() {
string target;
char s;
int k, i, num, length, j;
cin >> s >> k;
getline(cin, target);
for (j = 0; j <= (int)target.length(); j++) {
if ((target[j]) = ' ') {
target.erase(j, 1);
}
}
length = (int)target.length();
if (s == 'e') {
for (num = 0; num <= length; num++) {
if (isupper(target[num]))
target[num] = tolower(char(int(target[num] + k - 65) % 26 + 65));
else if (islower(target[num]))
target[num] = toupper(char(int(target[num] + k - 97) % 26 + 97));
}
}
else if (s == 'd') {
for (num = 0; num <= length; num++) {
if (isupper(target[num]))
target[num] = tolower(char(int(target[num] - k - 65) % 26 + 65));
else if (islower(target[num]))
target[num] = toupper(char(int(target[num] - k - 97) % 26 + 97));
}
}
cout << target;
return 0;
}
Let me put down the case which i failed to run.
input:
d 10 n 3 V 3 D 3 N _ M Y N 3 _ S C _ N 3 L E ( input d / e first, then shifting value, finally the sequence of string require to " change ", the space is required to delete. )
the expected output:
D3l3t3d_cod3_is_d3bu
my output:
D3l3:3d_cod3_i9_d3b;
Thanks!
Your issue is that when decoding you end up with negative numbers. With k == 13 the expression 'T' - k - 65 gives -7. -7 % 26 is still -7. -7+65 is 58 which isn't a letter.
You can avoid negative numbers by simply setting k to 26 - k when decoding.
Your code then simplifies to:
if (s == 'd') {
k = 26 - k;
}
for (num = 0; num <= length; num++) {
if (isupper(target[num]))
target[num] = tolower(char(int(target[num] + k - 'A') % 26 + 'A'));
else if (islower(target[num]))
target[num] = toupper(char(int(target[num] + k - 'a') % 26 + 'a'));
}
Note I've replaced your integer constants with their equivalent characters which makes the code much easier to understand.
Note you also have a bug in your first loop (target[j]) = ' ' should be (target[j]) == ' '.
Using all c++ has to offer you can reduce your code to:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string target = "mXLM";
char s = 'e';
int k = 7;
target.erase(std::remove(target.begin(), target.end(), ' '), target.end());
if (s == 'd') {
k = 26 - k;
}
std::string result;
std::transform(target.begin(), target.end(), std::back_inserter(result), [k](char in) {
if (isalpha(in)) {
char inputOffset = isupper(in) ? 'A' : 'a';
char outputOffset = isupper(in) ? 'a' : 'A';
return char(int(in + k - inputOffset) % 26 + outputOffset);
}
return in;
});
std::cout << result;
return 0;
}

Play With Numbers Programming Challenge (mean value of subarrays)

I'm trying to solve this Play with Numbers problem in Hackerearth. I have passed the test cases but, I kept getting time limit exceeded. Can someone help me improve its performance in order to pass the time limit, please?
This is my code -
#include <iostream>
using namespace std;
int main()
{
int n, q, i, l, r, j, sum;
cin >> n >> q;
int *arr = new int[n];
for (i = 0; i < n; i++)
{
cin >> arr[i];
}
for (i = 0; i < q; i++)
{
sum = 0;
cin >> l >> r;
for (j = l - 1; j <= r - 1; j++)
{
sum += arr[j];
}
cout << sum / (r - l + 1) << endl;
}
delete[] arr;
}
You have to remove the inner loop. Instead of storing the elements in the array, store the cumulative sum.
E. g. the elements are 1, 2 ,2, 1, 4.
You have to store 1, (1 + 2 =) 3, (1 + 2 + 2 =) 5, (1 + 2 + 2 + 1 =)6, (1 + 2 + 2 + 1 + 4 =) 10. Then you can calculate the sum of subarray with last_element - first_element.
E. g. for start index 2 and end index = 5 you get 2 + 2 + 1 + 4 = 10 - 1.
You don't need the inner loop.

I can't figure out a sum and numbers solution

I am not that skilled or advanced in C++ and I have trouble solving a problem.
I know how to do it mathematically but I can't write the source code, my algorithm is wrong and messy.
So, the problem is that I have to write a code that reads a number ( n ) from the keyboard and then it has to find a sum that is equal to n squared ( n ^ 2 ) and the number of sum's elements has to be equal to n.
For example 3^2 = 9, 3^2 = 2 + 3 + 4, 3 elements and 3^2 is 9 = 2 + 3 + 4.
I had several attempts but none of them were successful.
I know I'm borderline stupid but at least I tried.
If anyone has the time to look over this problem and is willing to help me I'd be very thankful.
1
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
//1,3,5,7,9,11,13,15,17,19,21,23,25,27..
int n;
list<int> l;
cin >> n;
if ( n % 2 == 0 ){
cout << "Wrong." << endl;
}
for ( int i = 1; i <= 99;i+=2){
l.push_back(i);
}
//List is full with 1,3,5,7,9,11,13,15,17,19,21,23,25,27..
list<int>::iterator it = find(begin(l),end(l), n);
}
2
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
// 3^2 = 2 + 3 + 4
// 7^2 = 4 + 5 + 6 + 7 + 8 + 9 + 10
int n;
int numbers[100];
for (int i = 0; i <= 100; i++){
numbers[i] = i;
}
cin >> n;
int requiredSum;
requiredSum = n * n;
//while(sum < requiredSum){
// for(int i = 1; i < requiredSum; i++){
// sum += i;
// sumnums.push_back(sum);
// }
//}
int sum = 0;
std::vector<int> sumnums;
while(sum < requiredSum){
for(int i = 1; i < requiredSum; i++){
sum += i;
sumnums.push_back(sum);
}
}
for(int i=0; i<sumnums.size(); ++i)
std::cout << sumnums[i] << ' ';
}
Update:
The numbers of the sum have to be consecutive numbers.Like 3 * 3 has to be equal to 2 + 3 + 4 not 3 + 3 + 3.
So, my first try was that I found a rule for each sum.
Like 3 * 3 = 2 + 3 + 4, 5 * 5 = 3 + 4 + 5 + 6 + 7, 7 * 7 = 4 + 5 + 6 + 7 + 8 + 9 + 10.
Every sum starts with the second element of the previous sum and continues for a number of elements equal to n - 1, like 3 * 3 = 2 + 3 + 4, 5 * 5 , the sum for 5 * 5 starts with 3 + another 4 elements.
And another algorithm would be #molbdnilo 's, like 3 * 3 = 3 + 3 + 3 = 3 + 3 + 3 - 1 + 1, 3 * 3 = ( 3 - 1 ) + 3 + ( 3 + 1 ), but then 5 * 5 = (5 - 2) + ( 5 - 1 ) + 5 + 5 + 1 + 5 + 2
Let's do a few special cases by hand.
(The division here is integer division.)
3^2: 9
2 + 3 + 4 = 9
x-1 x x+1
1 is 3/2
5: 25
3 + 4 + 5 + 6 + 7 = 25
x-2 x-1 x x+1 x+2
2 is 5/2
7: 49
4 + 5 + 6 + 7 + 8 + 9 + 10
x-3 x-2 x-1 x x+1 x+2 x+3
3 is 7/2
It appears that we're looking for the sequence from n - n / 2 to n + n / 2.
(Or, equivalently, n / 2 + 1 to n / 2 + n, but I like symmetry.)
Assuming that this is correct (the proof left as an exercise ;-):
int main()
{
int n = 0;
std::cin >> n;
if (n % 2 == 0)
{
std::cout << "Must be odd\n";
return -1;
}
int delta = n / 2;
for (int i = n - delta; i <= n + delta; i++)
{
std::cout << i << " ";
}
std::cout << std::endl;
}
If there is not constraints on what are the elements forming the sum, the simplest solution is just to sum up the number n, n times, which is always n^2.
int main()
{
int n;
cout<<"Enter n: ";
cin >> n;
for(int i=0; i<n-1; i++){
cout<<n<<"+";
}
cout<<n<<"="<<(n*n);
return 0;
}
Firstly, better use std::vector<> than std::list<>, at least while you have less than ~million elements (it will be faster, because of inside structure of the containers).
Secondly, prefer ++i usage, instead of, i++. Specially in situation like that
...for(int i = 1; i < requiredSum; i++)...
Take a look over here
Finally,
the only error you had that you were simply pushing new numbers inside container (std::list, std::vector, etc.) instead of summing them, so
while(sum < requiredSum){
for(int i = 1; i < requiredSum; i++){
sum += i;
sumnums.push_back(sum);
}
change to
// will count our numbers
amountOfNumbers = 1;
while(sum < requiredSum && amountOfNumber < n)
{
sum += amountOfNumbers;
++amountOfNumbers;
}
// we should make -1 to our amount
--amountOfNumber;
// now let's check our requirements...
if(sum == requiredSum && amountOfNumbers == n)
{
cout << "Got it!";
// you can easily cout them, if you wish, because you have amountOfNumbers.
// implementation of that I am leaving for you, because it is not hard ;)
}
else
{
cout << "Damn it!;
}
I assumed that you need sequential sum of numbers that starts from 1 and equals to n*n and their amount equils to n.
If something wrong or need explanation, please, do not hesitate to contact me.
Upd. amountOfNumber < n intead <=
Also, regarding "not starting from 1". You said that you know how do it on paper, than could you provide your algorithm, then we can better understand your problem.
Upd.#2: Correct and simple answer.
Sorry for such a long answer. I came up with a great and simple solution.
Your condition requires this equation x+(x+1)+(x+2)+... = n*n to be true then we can easily find a solution.
nx+ArPrg = nn, where is
ArPrg - Arithmetic progression (ArPrg = ((n-1)*(1+n-1))/2)
After some manipulation with only unknown variable x, our final equation will be
#include <iostream>
int main()
{
int n;
std::cout << "Enter x: ";
std::cin >> n;
auto squareOfN = n * n;
if (n % 2 == 0)
{
std::cout << "Can't count this.\n";
}
auto x = n - (n - 1) / 2;
std::cout << "Our numbers: ";
for (int i = 0; i < n; ++i)
std::cout << x + i << " ";
return 0;
}
Math is cool :)

Trouble with Beginner's C++ Game of Life Program

Background: I am quite a beginner at programming. This is what I have so far in my rough draft for the Game of Life:
#include <iostream>
using namespace std;
int main()
{
//INTRODUCTION
int arraySize;
cout << "What is the length of your square-shaped grid? Enter an integer value greater than 0. Too big will cause problems.";
cin >> arraySize;
int original[arraySize][arraySize];
//REQUESTS INPUT FOR ARRAY
for (int n = 0; n < arraySize; n++)
{
for (int x = 0; x < arraySize; x++)
{
bool ValInput;
cout << "\n" << n << "," << x << "...";
cin >> ValInput;
original[n][x] = ValInput;
}
}
cout << "\n\n\n";
//DISPLAYS ARRAY
for (int row = 0; row < arraySize; row++)
{
for (int column = 0; column < arraySize; column++)
{
cout << original[row][column] << " ";
if (column == arraySize - 1)
{
cout << "\n";
}
}
}
cout << "Next frame.\n\n";
//FORMS NEXT FRAME WITH VALUES OF # OF LIVE NEIGHBORS
int liveNeighbors = 0;
for (int z = 0; z < arraySize; z++)
{
for (int h = 0; h < arraySize; h++)
{
liveNeighbors = 0;
if (z - 1 > -1)
liveNeighbors += original[z - 1][h];
if (z + 1 < arraySize)
liveNeighbors += original[z + 1][h];
if (h - 1 > -1)
liveNeighbors += original[z][h - 1];
if (h + 1 < arraySize)
liveNeighbors += original[z][h + 1];
if (z - 1 > -1, h - 1 > -1)
liveNeighbors += original[z - 1][h -1];
if (z - 1 > -1, h + 1 < arraySize)
liveNeighbors += original[z - 1][h + 1];
if (z + 1 < arraySize, h - 1 > -1)
liveNeighbors += original[z + 1][h - 1];
if (z + 1 < arraySize, h + 1 < arraySize)
{
liveNeighbors += original[z + 1][h + 1];
}
cout << liveNeighbors << " ";
}
}
}
The problem appears in the last step I have made so far (which is showing how many live neighbors each cell has.
Example: If the sample input is first "4" for a 4x4 grid and then you enter in a variety of 1s and 0s, the liveNeighbors value is not realistic. It may be in the hundreds, when the maximum should be only 8.
If you could help me find a solution to my problem, that would be nice. However, please keep in mind that I am a novice.
Thank you :)
Some of your conditions are wrong :
if (z - 1 > -1, h - 1 > -1) /* ... */
if (z - 1 > -1, h + 1 < arraySize) /* ... */
if (z + 1 < arraySize, h - 1 > -1) /* ... */
if (z + 1 < arraySize, h + 1 < arraySize) /* ... */
The comma does not do what you expect, what you need is probably a logical 'and' which in C++ is the operator && :
if ((z - 1 > -1) && (h - 1 > -1)) /* ... */
if ((z - 1 > -1) && (h + 1 < arraySize)) /* ... */
if ((z + 1 < arraySize) && (h - 1 > -1)) /* ... */
if ((z + 1 < arraySize) && (h + 1 < arraySize)) /* ... */
Extra parenthesis added for readability only, they are not required.
Just so you know, this is the standard definition of the comma operator :
A pair of expressions separated by a comma is evaluated left-to-right and the value of the left expression is
discarded.
In your case, the comparisons on the left side of the commas were basically not playing any role in the if condition.
I think that your problem is in this code:
if (z - 1 > -1, h - 1 > -1)
Your intuition is completely correct here, but the way that you've written this in code doesn't mean what you want. In C++, the comma operator is an esoteric operator that means "do both things, but discard the result of the first operation.". In this case, that means "check if z - 1 > -1, then completely discard that result, then see whether h - 1 > -1," which isn't at all what you want. To check and see if both of these conditions hold true, use the && operator:
if (z - 1 > -1 && h - 1 > -1)
That should help fix your bug.
Hope this helps!