I want to program a function in C++ which does the same thing as the function histcounts in Matlab, but I don't get the right edges.
[V, edges]=histcounts(Vector,10);
I found this post : implementing matlab hist() in c++ and I created a function which I thought should work. How do I get the same edges in my function as in histcounts?
My Code :
int n =10;
double histogrammdistance = (ceil(*max_element(std::begin(Vector), std::end(Vector)))-floor(*min_element(std::begin(Vector), std::end(Vector))))/n;
vector<double> edges;
double minY = *min_element(std::begin(Vector), std::end(Vector));
for (int i = 0 ;i <=n; i++)
{
edges.push_back(floor(minY) + histogrammdistance * i);
}
So My Problem right now is :
i have this Vector = [-37,0329218106996 -26,9722222222222 -34,0823045267490 -33,0987654320988 -39 -35,0658436213992 -30,8061224489796 -36,0493827160494 -38,0164609053498 -12]
Matlab creates these edges :
edges [-40 -37,2000000000000 -34,4000000000000 -31,6000000000000 -28,8000000000000 -26 -23,2000000000000 -20,4000000000000 -17,6000000000000 -14,8000000000000 -12,0000000000000]
But my Program doesn't use -40 to calculate the binwidth..because the minimum number is -39 and not -40. Also if i change -39 to -38.5... matlab is still picking -40
1, Question : Why is Matlab taking -40 ... and has sb an idea how this could be implemented ?
i created now a very simpel Vector with [1 2 3 4 5] if i take 15 as bin number i get this as solution [1 1.27 1.54 1.81 ...] bit if i take 13 as bin number it doesn*t start with the min number 1 :/ it starts with [0,90 1,2 1,54 1,8 2,18....]
2. Question : do sb know why it took 0.90 ??
Related
Hello and thanks for helping!
So we've got a list of fireworks containing 1) Number in stock 2) Number of fireworks in this package 3) Diameter which equals the noise and
4) The price.
This is the list:
25 17 10 21
10 15 10 18
5 16 10 19
10 15 12 20
15 9 11 12
10 7 28 23
8 7 16 11
10 6 16 10
25 10 18 25
25 12 18 27
10 5 40 35
60 40 5 27
5 25 30 90
50 1 60 8
Our task is to create a shopping list and buy fireworks so we get the highest possible noise. We've got a knapsack capacity of 1000€. We're also supposed to solve this without using tables (so with dynamic programming instead).
I only use one class called Package which contains the four constraints as shown above.
At first I thought it would make sense to try to write an algorithm for a normal knapsack, so just with the price and the diameter (=weight). I tested it with a different list and it worked perfectly fine. I just iterated through all packages and then again used a nested for loop to find the best constellation (exhaustive search). My next idea was to merge the number of fireworks per package with the diameter, because fireworks can only be bought in a full package.
The only thing left which I still haven't found out is what to do with the amount of packages in stock. Like, with my current algorithm it just buys all packages of a firework until the knapsack is full. But obviously that won't be correct.
void knapsack(vector<Package*> stock){
vector<int> indices, tmp_indices;
int noise,tmp_noise= 0;
int price;
for (unsigned int i = 0; i < stock.size(); i++) {
price = stock[i]->price;
noise = stock[i]->diameter*stock[i]->number_fireworks;
indices.push_back(i);
for (unsigned int j = 0; j < stock.size(); j++) {
if (i != j) {
if (price+stock[j]->price<= BUDGET) {
price+=stock[j]->price;
noise+=stock[j]->diameter*stock[j]->number_fireworks;
indices.push_back(j);
}
}
}
// After second loop we have a new possible constellation
// Check if the previous constellation had a lower value and if so, set it to the current one
if (noise > tmp_noise) {
tmp_noise = noise;
tmp_indices.clear();
// tmp save
for (auto &index : indices) {
tmp_indices.push_back(index);
}
}
price= 0;
noise = 0;
indices.clear();
}
// Best constellation found, Print the shopping list
cout << "\Stock.\tNum\Diameter.\Price\n" << endl;
for(unsigned int i = 0; i < tmp_indices.size(); i++) {
cout << stock[tmp_indices[i]]->stock<< "\t";
cout << stock[tmp_indices[i]]->number_fireworks<< "\t";
cout << stock[tmp_indices[i]]->diameter<< "\t";
cout << stock[tmp_indices[i]]->price<< "\t\n";
}
}
We've been told that we should be able to spend exactly 1000€ to get the correct constellation of fireworks. My idea was to add another for loop to iterate through the amount of available packages, but that didn't really work...
This was our first lesson and I'm a bit desperate, because we have only learned how to solve a knapsack problem with 2 constraints and by using a table R.
Edit: Since one user insisted to get a specific question, here it is: Is the idea of using another loop to include the third constraint correct or is there a better/easier way of doing it? Or is it possible that I need a completely different approach for a knapsack with 3 instead of 2 constraints?
Thanks for help in advance
i am working through an EDX course on computer programming. I have come to this problem and dont know how to work through it. im not looking for an answer but more a point in the right direction.
so the question gives you a 2D array. two columns and N amount of rows. the N is the number of students. each column is the grade of first test and then the second is the grade of the second test. I am asked to find the root mean square of two seperate kids and compare them and then return a number based off the comparison. The question gives you this formula
RMS = (0.5×(midsem_marks2 + endsem_marks2))0.5
I know how to get the appropriate marks using array[index 1(firsttest)] etc and then how to compare them. However, i am clueless on how to write that formula. any help would be great. Thanks in advance.
code I have
float RMSi1 = sqrt(.5*((marksarray[index1][0]*marksarray[index1][0])+(marksarray[index1][1])*(marksarray[index1][1])));
float RMSi2 = sqrt(.5*((marksarray[index2][0]*marksarray[index2][0])+(marksarray[index2][1])*(marksarray[index2][1])));
if(RSMi1>RSMi2){
return -1;
}
if(RSMi1<RSMi2){
return 1;
}
if(RSMi1==RSMi2){
return 0;
}
I'm getting an error that the RSMi1 and 2 are not declared in the if statements
Input marksarray:
1 2
1 60 20
2 60 20
3 30 40
4 10 90
5 90 30
6 0 100
7 60 20
So I'm having a lot of trouble understanding c++ again I've taken my programming class twice and failed. I need help. I'm not interested in programming anymore because it's obviously not for me. I just need to pass. Here's the problem:
The goal of this assignment is to practice recursive algorithms by writing a program that takes in a matrix representing the number of guards in each room of the castle and outputs the fastest path to the princess and the number of guards you will have to fight.
You're moving through a map(array) that looks like:
5 5
6 2 3 44 15
1 7 2 9 10
11 1 5 14 12
5 17 2 1 20
21 7 33 4 25
Where the first to numbers are the size of your array and you can only move right and down.
So an output would be:
50 > > v v v > v >
We're given a skeleton which we have to fill in but I don't know what some of it does and it might be too long to copy and paste here, I'm new to the community.
How would you tackle this assignment
Using recursion you try to simplify the problem. So take a step right, compute the score for this step and add it to the rest of the solution by calling the same function on a smaller matrix (leaving out the left column). Then take a step down and do the same with the smaller matrix leaving out the top row. Then choose the solution with the lowest score.
This is just a dynamic programming problem.
I don't know how to pass a 2-d array as a function parameter.
Someone correct me please(How to pass 'matrix' array and 'result' array as function parameters). Rest all part is fine
Algorithm is simple. Just start from the last position and come backwards.
where result[i][j] = min(result[i+1][j],result[i][j+1])
void function(int a,int b,int** matrix,int** result){
if(result[a+1][b] == -1 && result[a][b+1] == -1){
result[a][b] = min(function(a+1,b,matrix,result),function(a,b+1,matrix,result));
}
else if(result[a+1][b] == -1 && result[a][b+1] != -1){
result[a][b] = min(function(a+1,b,matrix,result),result[a][b+1]);
}
else if(result[a+1][b] != -1 && result[a][b+1] == -1){
result[a][b] = min(result[a+1][b],function(a,b+1,matrix,result));
}
return;
}
int main(){
int p,q;
cin>>p>>q;
int matrix[p][q];
for(int i=0;i<p;i++){
for(int j=0;j<q;j++){
cin>>matrix[i][j];
}
}
int result[p][q];
for(int i=0;i<p;i++){
for(int j=0;j<q;j++){
result[i][j] = -1;
}
}
result[p-1][q-1] = matrix[p-1][q-1];
for(int i=q-2;i>=0;i++){
result[p-1][i] = matrix[p-1][i] + result[p-1][i+1];
}
for(int i=p-2;i>=0;i++){
result[i][q-1] = matrix[i][q-1] + result[i+1][q-1];
}
function(0,0,matrix,result);
cout<<results[0][0]<<endl;
}
I was solving Counting Subsequence Problem in spoj, but getting Wrong Answer. here is the link http://www.spoj.com/problems/SUBSEQ/
Here is my code
#include<stdio.h>
#include<cmath>
#include<algorithm>
int main(){
int t,n;
scanf("%d",&t);
while(t-->0){
scanf("%d",&n);
long arr[n+1];
for(int i=0;i<n;i++){
scanf("%ld",&arr[i]);
}
long sum=arr[0];
int start=0;
long ans=0;
for(int i=1;i<=n;i++){
while(sum>47 && start<i-1){
sum-=arr[start];
start++;
}
if(sum==47)
ans+=1;
if(i<n)
sum+=arr[i];
}
printf("%ld\n",ans);
}
}
Please help me find the error ..
You code will fail the following test case (at least):
1
4
47 -47 48 -1
Your programs gives the answer as 1, where as the answer should be 3, where 3 sequences as follows:
47 -47 48 -1 [The entire sequence]
47 [1st element only]
48 -1 [3rd plus 4th elements]
So, clearly, you've got bugs.
PS: BTW, why are you declaring an array of n+1 items: long arr[n+1]; when you are never going to reference arr[n]? (in fact that item won't even exist)
[Edit]#: Adding explanation for the above use case
How about this - Its easier than you think :-)
Scan the numbers serially. For each number encountered, add it to sum found so far.
Keep a map of number of times the sum (so far) has been found.
Now, to make a total of 47, all we need is to find a number, which when subtracted from the sum so far should give number 47. This is required because if we subtract such number from sum found so far, it would yield 47 obtained from summation of some sequence(s) of contiguous numbers.
Take the above example, 47 -47 48 -1
Initialize a map with number 0 having count = 0 (That's to say that we have found no sum so far exactly once - since we are at the begining)
Scanning the list from the beginning, take number 47, sum so far, say, s = 47. We do 2 things:
map(47) = 1 (since we've found sum so far = 47 for first time).
Now, we need to find number of times, we've can find s-47 = 0 (which is 1). So, answer so far = map(0) = 1
Take next number, -47. Sum so far, s = 0
map(0) = 1 so far, so no map(0) becomes = 2
We need to find number of occurrences of s-47 = -47. Which = 0. So answer so far = answer so far + 0 (remains = 1)
Take next number, 48, sum so far, s = 48
map(48) = 1
We need to find number of occurrences of s-48 = -1. Which = 0. So answer so far = answer so far + 0 (remains = 1)
Take last number, -1, sum so far, s = 47
map(47) = 1 (in step 2.1), so now map(47) becomes = 2
We need to find number of occurrences of s-47 = 0. Which = 2 (in step 3.1). So answer so far = answer so far + 2 = 3
So final answer = 3
It should be fairly trivial to code this.
I have Visual Studio 2012 with Intel parallel studio 2013 installed, so I have Intel TBB.
Say I have the following piece of code:
const int cardsCount = 12; // will be READ by all threads
// the required number of cards of each colour to complete its set:
// NOTE that the required number of cards of each colour is not the same as the total number of cards of this colour available
int required[] = {2,3,4}; // will be READ by all threads
Card cards[cardsCount]; // will be READ by all threads
int cardsIndices[cardsCount];// this will be permuted, permutations need to be split among threads !
// set "cards" to 4 cards of each colour (3 colours total = 12 cards)
// set cardsIndices to {0,1,2,3...,11}
// this variable will be written to by all threads, maybe have one for each thread and combine them later?? or can I use concurrent_vector<int> instead !?
int logColours[] = {0,0,0};
int permutationsCount = fact(cardsCount);
for (int pNum=0; pNum<permutationsCount; pNum++) // I want to make this loop parallel !!
{
int countColours[3] = {0,0,0}; // local loop variable, no problem with multithreading
for (int i=0; i<cardsCount; i++)
{
Card c = cards[cardsIndices[i]]; // accessed "cards"
countColours[c.Colour]++; // local loop variable, np.
// we got the required number of cards of this colour to complete it
if (countColours[c.Colour] == required[c.Colour]) // read global variable "required" !
{
// log that we completed this colour and go to next permutation
logColours[c.Colour] ++; // should I use a concurrent_vector<int> for this shared variable?
break;
}
}
std::next_permutation(cardsIndices, cardsIndices+cardsCount); // !! this is my main issue
}
What I'm calculating is how many times we will complete a colour if we pick randomly from available cards, and that's done exhaustively by going through each permutation possible and picking sequentially, when a colour is "complete" we break and go to the next permutation. Note that we have 4 cards of each colour but the required number of cards to complete each colour is {2,3,4} for Red, Green, Blue. 2 red cards are enough to complete red and we have 4 available, hence red is more likely to be completed than blue which requires all 4 cards to be picked.
I want to make this for-loop parallel, but my main problem is how to deal with "cards" permutations? you have ~0.5 billion permutation here (12!), if I have 4 threads how can I split this into 4 different quarters and let every thread go through each of them?
What if I don't know the number of cores the machine has and I want the program to automatically choose the right number of concurrent threads? surely there must be a way to do that using Intel or Microsoft tools?
This is my Card struct just in case:
struct Card
{
public:
int Colour;
int Symbol;
}
Let N = cardsNumber, M = required[0] * required[1] * ... * required[maxColor].
Then, actually, your problem could be easily solved in O(N * M) time. In your very case, that is 12 * 2 * 3 * 4 = 288 operations. :)
One of possible ways to do this is to use a recurrence relation.
Consider a function logColours f(n, required). Let n be the current number of already considered cards; required is a vector from your example. Function returns the answer in a vector logColours.
You are interested in f(12, {2,3,4}). Brief recurrent calculation inside a function f could be written like this:
std::vector<int> f(int n, std::vector<int> require) {
if (cache[n].count(require)) {
// we have already calculated function with same arguments, do not recalculate it again
return cache[n][require];
}
std::vector<int> logColours(maxColor, 0); // maxColor = 3 in your example
for (int putColor=0; putColor<maxColor; ++putColor) {
if (/* there is still at least one card with color 'putColor'*/) {
// put a card of color 'putColor' on place 'n'
if (require[putColor] == 1) {
// means we've reached needed amount of cards of color 'putColor'
++logColours[putColor];
} else {
--require[putColor];
std::vector<int> logColoursRec = f(n+1, require);
++require[putColor];
// merge child array into your own.
for (int i=0; i<maxColor; ++i)
logColours[i] += logColoursRec[i];
}
}
}
// store logColours in a cache corresponding to this function arguments
cache[n][required] = std::move(logColours);
return cache[n][required];
}
Cache could be implemented as an std::unordered_map<int, std::unordered_map<std::vector<int>, std::vector<int>>>.
Once you understand the main idea, you'll be able to implement it in even more efficient code.
You can easy make your code run in parallel with 1,2, ..., or cardsCount threads by fixing the first element of permutation and calling std::next_permutation on other elements independently in each threads.
Consider the following code:
// declarations
// #pragma omp parallel may be here
{ // start of a parallel section
const int start = (cardsCount * threadIndex) / threadNumber;
const int end = (cardsCount * (threadIndex + 1)) / threadNumber;
int cardsIndices[cardsCount]; // a local array for each thread
for (const int firstElement = start; firstElement < end; ++firstElement) {
cardsIndices[0] = firstElement;
// fill other cardsIndices with elements [0-cardsCount], but skipping firstElement
do {
// your calculations go here
} while (std::next_permutation(cardsIndices + 1, cardsIndices + cardsCount)); // note the +1 here
}
}
If you wish to use OpenMP as a parallelization tool, you only have to
add #pragma omp parallel just before the parallel section. And use
omp_get_thread_num() function to get a thread index.
You also do not have to use a concurrent_vector here, this would
probably make your program extremely slow, use a thread-specific
accumulation array:
logColours[threadNumber][3] = {};
++logColours[threadIndex][c.Colour];
If Card is a rather heavy class, I would suggest using const Card& c = ... instead of copying each time Card c = ....
I guess this is an amateur friendly version of what #Ixanezis means
If red wins
the final outcome will be: 2 red, 0-2 green, 0-3 blue
Say the winning red is A, and the other red is B, there are 12 ways to get A and B.
The following are the possible cases:
Cases: #Cards after A #Cards before A #pick green #pick blue
0 green, 0 blue: 10! = 3628800 1! = 1 1 1
0 green, 1 blue: 9 ! = 362880 2! = 2 1 4
0 green, 2 blue: 8 ! = 40320 3! = 6 1 6
0 green, 3 blue: 7 ! = 5040 4! = 24 1 4
1 green, 0 blue: 9 ! = 362880 2! = 2 4 1
1 green, 1 blue: 8 ! = 40320 3! = 6 4 4
1 green, 2 blue: 7 ! = 5040 4! = 24 4 6
1 green, 3 blue: 6 ! = 720 5! = 120 4 4
2 green, 0 blue: 8 ! = 40320 3! = 6 6 1
2 green, 1 blue: 7 ! = 5040 4! = 24 6 4
2 green, 2 blue: 6 ! = 720 5! = 120 6 6
2 green, 3 blue: 5 ! = 120 6! = 720 6 4
Lets sumproduct those 4 arrays: = 29064960, then multiply by 12 = 348779520
Similarly you can calc for green wins for blue wins.
You can use std::thread::hardware_ concurrency() from <thread>. Quoting from "C++ Concurrency in action" by A.Williams -
One feature of the C++ Standard Library that helps here is
std::thread::hardware_ concurrency(). This function returns an
indication of the number of threads that can truly run concurrently
for a given execution of a program. On a multicore system it might be
the number of CPU cores, for example.