Returning position of int [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
The task is to return the leftmost position of given int A in larger int B (counting from 0)
A = 53, B = 1953786,
return: 2
I've found similar problem, but in that solution java function "indexOf" was used, is there a possibility to do it in other way?

The easiest way to do this would be to convert them both to std::string, and then you can use functions of std::string to find the index, similar to how you'd have indexOf for Java.
#include <iostream>
#include <string>
int main()
{
int a = 53;
int b = 513953786;
std::string number = std::to_string(b);
std::string numberToFind = std::to_string(a);
auto index = number.find(numberToFind);
std::cout << index;
}
This will return 4, since I moved the 53 to be at the 4th index to show it won't find the earlier 5 or 3 I added, per the advice of #Blastfurnace in the comments

What about using the c++ function: std::find()? You could then do something like this:
int getIndex(int a, int b){
std::string a_str = std::to_string(a);
std::string b_str = std::to_string(b);
return a_str.find(b_str);
}

Related

What does 'dict' do in c++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I was looking at a solution for this problem:
Given a string s, find the length of the longest substring without repeating characters.
The following solution was posted, but I am having trouble understanding what dict does. I've tried looking for documentation in C++. However, I have not found anything. Can someone explain how it works, and where I can find documentation?
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1);
int maxLen = 0, start = -1;
for (int i = 0; i != s.length(); i++) {
if (dict[s[i]] > start)
start = dict[s[i]];
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}
dict is just the name that was used for this vector<int>, first parameter is the the size of vector, second is value that should be assigned to all of its positions.
This is one of the possible ways to use its constructor, check the example on this page.

How to decide is it a string or not? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
I have an array of strings and I'd like to assort the elements by real datatype ("1" -> int; "abc" -> string; "1a" -> string) :
#include <iostream>
#include<vector>
int main() {
std::vector<std::string> number;
std::vector<std::string> str;
std::string arr[5] = {"1","1a","ab","10.1","a2"};
for(int i = 0;i<5;i++){
if(arr[i] /* is string */){
str.push_back(arr[i]);
}
else if(arr[i] /* is int */){
number.push_back(arr[i]);
}
}
return 0;
}
What is the simplest way?
Thanks!
If your goal is to only examine whether a string contains integer/decimal or not, you can try a solution with regexes:
if(std::regex_match(arr[i], std::regex("[-|+]?[0-9]*[.,]?[0-9]+")))
number.push_back(arr[i]);
else
str.push_back(arr[i]);
I'm assuming you're not taking overflow into account because you're only using strings, otherwise if you wanted to convert strings to numbers, you'd have to take that into account and use other solutions.

memoizing a recursion solution (DP) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have written this recursion for the problem https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee
I want to know how can we memoize this solution (using a dp array).
or do we have to write recursion in a specific way to memoize it?
class Solution {
public:
int solve(vector<int>& prices,int fee,int i,int profit,int buy,int sell)
{
if(i==prices.size())
{
if(buy==sell)
return profit;
else
return 0;
}
int ans = 0;
ans = max(ans,solve(prices,fee,i+1,profit,buy,sell));
if(buy>sell)
{
ans = max(ans,solve(prices,fee,i+1,profit+prices[i]-fee,buy,sell+1));
}
else
{
ans = max(ans,solve(prices,fee,i+1,profit-prices[i],buy+1,sell));
}
return ans;
}
int maxProfit(vector<int>& prices, int fee) {
vector<int> diff;
int sum = 0;
sum = solve(prices,fee,0,0,0,0);
return sum;
}
};
You can just create an array where element i is equal to solve(i). Then, inside your function, you can pass this array through by reference to each call. You add an if/else structure in your function testing if the input you got was defined in the array, if so return arr[input] and if not, run through your normal function except just before you return, you initialize arr[input] to the value you will return.

Find the closest object from your position on a proper way QT c++ [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to find the closest Healthpacks or enemy from a player's position. I have wrote this like:
for(auto &hp : model->getAllHealthPacks()){
if(!hp->getUsed()){
int x = hp->getXPos();
int y = hp->getYPos();
int q = (x*x)+(y*y);
if(q < smallest){
smallest = z;
hpfound = hp;
foundAHp++;
}
}
}
Now I was wondering, this is actually not proper. Are there better and profesional way's to improve my code? (Lambda,...)?
The code in general is not bad, but there is some room for improvement. First, you could make the variable hp a constant since you are not modifying its contents.
You could also create a class to store the coordinates in a single object like this
class Coordinate{
std::pair<int,int> coords;
...
};
The final code could look like this:
for(const auto &hp : model->getAllHealthPacks()){
if(!hp->getUsed()){
Coordinate coord(hp->getCoord());
int q = coord.getX()*coord.getX()+coord.getY()*coord.getY();
if(q < smallest){
smallest = z;
hpfound = hp;
foundAHp++;
}
}
}
You should also rename q to something more clear for future reference.

Access elements of 2D array with absolute element number [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a 2-Dimensional array whose elements I typically want to access like this:
val = my_array[row][col];
But I also have need to access elements using their absolute index from time to time, where the row and column are not known. The "absolute" index of a given element can be computed as follows:
abs_idx = row*numCols + col;
I am thinking of achieving this as follows
mydatatype *my_array_abs = new mydatatype[numRows*numCols];
mydatatype **my_array = new mydatatype*[numRows];
for (int ii=0; ii<numRows; ii++)
{
my_array[ii] = &my_array_abs[ii*numCols];
}
Is this an appropriate way to achieve my goal, or should I expect to run into any problems or inefficiencies?
To achieve what you want you need to change your line:
mydatatype *my_array;
To:
mydatatype **my_array = new mydatatype*[numRows] ;
Note: I see only one issue with this approach that, you required continuous memory chunk.
Otherwise your approach is perfectly fine.
I'd be tempted to use std::vector to avoid all the hazards of raw arrays:
#include <vector>
#include <iostream>
typedef int mydatatype;
typedef std::vector<std::vector<mydatatype> > myvectortype;
int numCols = 10;
int numRows = 100;
mydatatype& at_absolute(myvectortype& v, int index) {
return v[index / numRows][index % numRows];
}
int main() {
myvectortype my_array(numRows, std::vector<mydatatype>(numCols, 0));
my_array[1][2] = 31;
std::cout << at_absolute(my_array, 102) << '\n';
}