Previously, I was using append function to concatenate strings.
However, since doing so requires multiple lines of unnecessary codes, I wanted to try out '+' operator instead. Unfortunately, it didn't go well...
bool Grid::is_available(int x, int y) const
{
if (x < 0 || x >= dim[1] || y < 0 || y >= dim[0])
throw std::invalid_argument("is_available(" + x + ", " + y + "): Invalid coordinate input.");
return occupancy[x][y] == AVAILABLE;
}
The error that I got was "'+': cannot add two pointers" with the code C2110.
All the solutions for this problem said to concatenate one on each line.
Are there actually no way to concatenate multiple strings in C++ in one line? I had no problem with this in C# before.
You can use std::to_string() to convert your integers:
bool Grid::is_available(int x, int y) const
{
if (x < 0 || x >= dim[1] || y < 0 || y >= dim[0])
throw std::invalid_argument(
"is_available(" + std::to_string(x) + ", "
+ std::to_string(y) + "): Invalid coordinate input.");
return occupancy[x][y] == AVAILABLE;
}
Related
bool isValid(int x, int y, vector<vector<int>> &arr)
{
if (x >= 0 && x <= arr.size() && y >= 0 && y <= arr[0].size() && arr[x][y] == 1)
return true;
return false;
}
I am getting segmentation fault on this ( x <= arr.size() and y<=arr[0].size() ) of the code.
Can you guys please explain why I am getting this even if I am not accessing the out of bound value and I am just comparing it.
Packing too many conditions into one is not always good. Splitting it up in several conditions can help with debugging. Simple code is not always less code.
bool isValid(int x, int y, vector<vector<int>> &arr) {
// first index is ok?
if (x < 0) return false;
if (x >= arr.size()) return false;
// only now you can access arr[x]
if (y < 0) return false;
if (y >= arr[x].size()) return false;
// both are ok
return arr[x][y] == 1;
}
In your code you are checking arr[0] not arr[x], when all inner vectors are of same size you can consider to use a different data structure. Even when you know that all inner vectors of same size you should nevertheless check arr[x] not arr[0]. Also consider to use size_t (it is unsigned) for the indices, then you can remove the checks for <0.
Your code can segfault because the last valid index is size -1 not size and because arr[0] does not necessarily have same number of elements as arr[x].
What if x == 0 and arr.size() == 0?
In this case, you'll fail on accessing arr[0] inside the y <= arr[0].size() expression, because you are trying to access the vector object present in arr[0] while such thing does not exist.
To be more general, you have to note that accessing arr[x][y] is not valid if x == arr.size() or y == arr[x].size(), but you're allowing such situation by x <= arr.size() and y <= arr[0].size() in your conditions. Your function would finally look like something like this:
bool isValid(int x, int y, vector<vector<int>> &arr)
{
if (x >= 0 && x < arr.size() && y >= 0 && y < arr[x].size() && arr[x][y] == 1)
return true;
return false;
}
why I am getting this even if I am not accessing the out of bound value and I am just comparing it [?]
Consider y <= arr[0].size(), here you are not just comparing, but accessing the first element of arr and retrieving its size. The problem is that arr may be empty, so that arr[0] would be an access out of bounds.
Also, using <= is an off-by-one error, because size() - 1 is the last valid index.
That function could be rewritten like the following
bool isValid(int x, int y, std::vector<std::vector<int>> const& m)
{
return x >= 0 and x < m.size() and
// ^
y >= 0 and y < m[x].size() and
// ^ ^^^ Are all the same size?
m[x][y] == 1;
}
I was trying to solve this problem and from the comments section in the editorial, I was directed to the following solution :
#include <bits/stdc++.h>
using namespace std;
#define MAX(a,b,c) max(a,max(b,c))
int n,a,b,c,dp[4001];
int f(int x)
{
if (x == 0) return 0;
if (x < 0 || (x > 0 && x < a && x < b && x < c))
return 0xACCE97ED; // <- **I have doubt here**
if (!dp[x]) dp[x] = MAX(f(x-a),f(x-b),f(x-c)) + 1;
return dp[x];
}
int main()
{
cin >> n >> a >> b >> c;
memset(dp,0,sizeof(dp));
cout << f(n) << endl;
}
I wanted to know:
What is the need of the if statement that returns 0xACCE97ED for the test case:
4000 1 2 3. This test case dosen't work when that specific if statement is missing.
Why specifically 0xACCE97ED is being returned? Because when I tried to return any other number (say 9999), then the output is expected output + 9999.
if (x < 0 || (x > 0 && x < a && x < b && x < c))
return 0xACCE97ED; // -1395746835
Well looking at the dp function, it is basically maximizing values and this specific if statement is saying:
if x < 0
the length of the ribbon you cut is negative (which should be impossible)
or if x > 0 and x < a, b, c which means you can still cut X but all available sizes would result into having a ribbon of negative length
return 0xACCE97ED; return a random negative value which happens to spell out ACCEPTED because this state is invalid
And since the third if statement will try to get the max value, 0xACCE97ED will never be selected as the max value.
0xACCE97ED means "ACCEPTED" in the 1ee7 speech. nothing else specific about this value.
What is the need of the if statement that returns 0xACCE97ED for the test case: 4000 1 2 3
if (x < 0 || (x > 0 && x < a && x < b && x < c))
return 0xACCE97ED; // <- **I have doubt here**
because the function f is recursive, in the next line it calls itself:
if (!dp[x]) dp[x] = MAX(f(x-a),f(x-b),f(x-c)) + 1;
return dp[x];
with a smaller values for x so presumable it will eventually make that if statement true and will return "accepted" (0xACCE97ED).
I'm trying to do a certain counter for my assignment but I tried many methods but i still can't figure them out.
My program allows users to find out the type of triangle based on their input.
So i do have 2 main functions to determine the shape of the triangle and to display the counter.
char shapeTriangle(int, int, int); //determine shape of triangle i.e isosceles ('I'), equilateral ('E')
int summaryDisplay(char); // display counter
In my shapeTriangle function, i have a simple if else statement that returns the type based on the user input
char shapeTriangle(int x, int y, int z)
{
char type;
if (x == y && y == z && x == z)
type = 'E';
else if (x == y || y == z || x == z)
type = 'I';
return type;
}
Over at my main function, i have loop that allows user to input till one of the value is a 0.
In summaryDisplay, i'm trying to count the number of times a certain triangle is determined
int finalSum(char type)
int eCount = 0, iCount = 0;
if (type == 'E')
eCount++;
if (type == 'I')
iCount++;
cout << "Equilateral" << eCount;
cout << "Isosceles" << iCount;
}
I managed to obtain an output however, the counter returns me some weird values like 540934 or 3453 etc etc which i can't really figure them out.
This is how i attempt to call my function in my int main
int main()
{
int x, y, z;
do{
cout << "Enter 3 intgers : ";
cin >> x >> y >> z;
//some display output codes
}while ( x != 0 && y != 0 && z != 0);
finalSum(shapeTriangle(x, y, z));
}
Any help is appreciated.
EDIT 1 : I tried initializing but however, it returns me 0 for all different types.
Just initialize your counters with Zero which will behave as your counter starting value. Like this:
int eCount = 0, iCount = 0;
Also, what would you like type to be if none of your conditions met? Because if you did not initialize type and none of your conditions met (if (x == y && y == z && x == z) and if (x == y || y == z || x == z)) then later both of your counters will stay 0.
You have to initialize your variables.
You don't have a default value for type. What if all three input values are different? No values are assigned to type in your if statements and this is not initialised.
Try to put a default value like 'U' for unknown...
It lookes like you've declared eCount and iCount inside the scope of finalSum(). This means that their values, if not initialized, will be garbage from previous activity on the stack, which is what you're seeing. Try declaring them globally, to preserve their values across function calls.
You should make sure that your counting variables are properly declared and initialized before they are incremented, otherwise you are wading into undefined behavior.
I'm running a bit of code where I need to compare two 2D arrays for any variance. I've tried using the following line of code to check and compare the values, but the test fails every time = if(arr1[a][b] != arr2[a][b] || arr1[a][b] + .1 != arr2[a][b] || arr1[a][b] - .1 != arr2[a][b]) {.
I know this is failing because of the || statement, because one of the requirements is met. So I've got to find another way to determine if the double stored in a specific location in the array matches the other array in the parallel location.
Here's my full code:
int numberOfFailedCompares = 0;
for(int a = 0; a < 20; a++) {
int b = 0;
while(b < 20) {
if(arr1[a][b] != arr2[a][b] || arr1[a][b] + .1 != arr2[a][b] || arr1[a][b] - .1 != arr2[a][b]) {
numberOfFailedCompares++;
cout << numberOfFailedCompares << endl;
}
b++;
}
}
Is there a statement in C++ which will allow me to check if the value is within the +/- .1 threshold? Something like
if(arrLocation1 (+/- .1) == arrLocation1) {
...
}
"Variance" means "within X", and not "equal to something plus X or something minus X". Instead of comparing for equality, you compare for less/greater than your variance. So, for example, to test for variance of +/- .1:
if (b >= a-.1 && b <= a+.1)
How about this?
#define eps .1
...
if( fabs(x-y) <= eps )
...
The code runs correctly and it does what it is supposed to do, but I was told I could make it faster by using Boolean expressions instead but would not really know where to insert them here. The problem is:
Given a sequence of n points with their coordinates, write a program remote, which calculates the value of the smallest remoteness of a point, which is outside the square. A point is outside the square, if it is neither inner to the square, nor belongs to square contour. If there are no points outside the square, your program has to output 0.
Constraints:
1 ≤ n ≤ 10000 and 1 ≤ a ≤ 1000 ;
Example:
Input:
5 4
1 2
4 6
-3 2
-2 2
4 -1
Output: 5
Could someone suggest me any technique to make the code more efficient?
int remote(int x, int y) {
int z = abs(x) + abs(y);
return z;
}
int main() {
int n, a;
int x;
int y;
cin >> n >> a;
int z=20001;
for (int i = 1; i <= n; i++) {
cin >> x >> y;
if (x > a / 2 || y > a / 2) {
if (z > remote(x, y)) {
z = remote(x, y);
}
}
}
cout << z <<endl;
return 0;
}
For one, you are calling remote twice (in some cases) needlessly.
Consider using this:
#include <algorithm>
z = std::max(z, remote(x, y));
This will also shorten and clarify the code.
Also, it's possible the divisions are slow. Try (after profiling!) replacing
x > a / 2 || y > a / 2
by
(x << 1) > a || (y << 1) > a
Note #Donnie & others claims in the comments that compilers will do the latter optimization, and they are probably correct.
I would like to show you the timings on my machine:
Version 1:
for (int i = 1; i <= n; i++) {
cin >> x >> y;
if (x > a / 2 || y > a / 2) {
if (z > remote(x, y)) {
z = remote(x, y);
}
}
}
Version 2:
for (int i = 1; i <= n; i++) {
cin >> x >> y;
/* if (x > a / 2 || y > a / 2) {
if (z > remote(x, y)) {
z = remote(x, y);
}
}
*/
}
For n=10^5, compiled with -O3 both yield 60ms. Compiled without optimization: both 60ms.
First step for optimizing is to know where your program spends time. Reading/parsing the data is the bottle neck.
You could speed up it a little bit by adding as first line to your main:
ios_base::sync_with_stdio(false);
On my machine I'm down to 20ms.
1) Assign a temporary value to the remote function:
if (x > a / 2 || y > a / 2)
{
const int r = remote(x,y);
if (z > r)
{
z = r;
}
}
2) Replace the call to remote with the contents of remote, removing the overhead of a function call:
if (x > a / 2 || y > a / 2)
{
const int r = abs(x) + abs(y);
if (z > r)
{
z = r;
}
}
3) Replace a / 2 with a constant temporary variable:
const int midpoint = a >> 1;
if (x > midpoint || y > midpoint)
4) Change compiler optimization level to high - for speed.
5) The bottleneck is now in the input statement. Any gain by optimizing the remainder of the loop is wasted by the Input time. There is no more Return On Investment for further changes.