calculating each line in 2d arrays c++ - c++

I'm trying to create an array loop using pointers. For example,
2 3 1 2
3 1 2 2
4 3 2 2
The number of lines are undetermined so we don't know how many lines of integers there will be. I have these data of integers stored into a pointer variable called "scores". So if I want to access them,
scores[0][0] = 2
scores[0][2] = 1
I'm trying to create a for loop where it will add each integer divide it by 2 and then add the sum up. So if I implement a function where it does this, i'd expect the value to be
4 // (2/2) + (3/2) + (1/2) + (2/2) = 4
4
5.5
This is what I have so far, but it's not working.
int *total;
int lines;
total = new int[lines]; //lines: how many lines there are (assume it is passed through a parameter)
for (int i=0;i<lines;i++)
{
for (int j=0;j<howmany;j++) //howmany is how many integers there are per line (assume it is passed again)
{
total[i] = scores[i][j] //not sure how to divide it then accumulate the sum per line and store it
Assume that "scores" already hold the data of integers and we're extracting the data of integers elsewhere so the user does not input anything.
I would want to access the calculated sum by doing total[0], total[1], etc..

For integer division
// (2/2) + (3/2) + (1/2) + (2/2) = 4
this will give 3, not 4
this will give you 4
// (2 + 3 + 1 + 2 ) / 2 = 4
And you are expecting value such as 5.5, so you should define the result as float or double
float *result;
int lines = 3; // need to initialize local variable before new. for this case, we set the lines to 3.
int total;
result = new float[lines]; //lines: how many lines there are (assume it is passed through a parameter)
for (int i=0;i<lines;i++)
{
total = 0;
for (int j=0;j<howmany;j++) //howmany is how many integers there are per line (assume it is passed again)
{
total += scores[i][j];
}
result[i] = (float)total/2;
}

Related

Populating a vector with numbers and conditions in C++

Working on a business class assignment where we're using Excel to solve a problem with the following setup and conditions, but I wanted to find solutions by writing some code in C++ which is what I'm most familiar from some school courses.
We have 4 stores where we need to invest 10 million dollars. The main conditions are:
It is necessary to invest at least 1mil per store.
The investments in the 4 stores must total 10 million.
Following the rules above, the most one can invest in a single store is 7 million
Each store has its own unique return of investment percentages based off the amount of money invested per store.
In other words, there is a large number of combinations that can be obtained by investing in each store. Repetition of numbers does not matter as long as the total is 10 per combination, but the order of the numbers does matter.
If my math is right, the total number of combinations is 7^4 = 2401, but the number of working solutions
is lesser due to the condition that each combination must equal 10 as a sum.
What I'm trying to do in C++ is use loops to populate each row with 4 numbers such that their sum equals 10 (millions), for example:
7 1 1 1
1 7 1 1
1 1 7 1
1 1 1 7
6 2 1 1
6 1 2 1
6 1 1 2
5 3 1 1
5 1 3 1
5 1 1 3
5 1 2 2
5 2 1 2
5 2 2 1
I'd appreciate advice on how to tackle this. Still not quite sure if using loops is a good idea whilst using an array (2D Array/Vector perhaps?) I've a vague idea that maybe recursive functions would facilitate a solution.
Thanks for taking some time to read, I appreciate any and all advice for coming up with solutions.
Edit:
Here's some code I worked on to just get 50 rows of numbers randomized. Still have to implement the conditions where valid row combinations must be the sum total of 10 between the 4;
int main(){
const int rows = 50;
int values[rows][4];
for (int i = 0; i < 50; i++) {
for (int j = 0; j <= 3; j++){
values[i][j]= (rand() % 7 + 1);
cout << values[i][j] << " ";
}
cout << endl;
}
}
You can calculate this recursively. For each level, you have:
A target sum
The number of elements in that level
The minimum value each individual element can have
First, we determine our return type. What's your final output? Looks like a vector of vectors to me. So our recursive function will return a the same.
Second, we determine the result of our degenerate case (at the "bottom" of the recursion), when the number of elements in this level is 1.
std::vector<std::vector<std::size_t>> recursive_combinations(std::size_t sum, std::size_t min_val, std::size_t num_elements)
{
std::vector<std::vector<std::size_t>> result {};
if (num_elements == 1)
{
result.push_back(std::vector<std::size_t>{sum});
return result;
}
...non-degenerate case goes here...
return result;
}
Next, we determine what happens when this level has more than 1 element in it. Split the sum into all possible pairs of the "first" element and the "remaining" group. e.g., if we have a target sum of 5, 3 num_elements, and a min_val of 1, we'd generate the pairs {1,4}, {2,3}, and {3,2}, where the first number in each pair is for the first element, and the second number in each pair is the remaining sum left over for the remaining group.
Recursively call the recursive_combinations function using this second number as the new sum, and num_elements - 1 as the new num_elements to find the vector of vectors for the remaining group, and for each vector in the return vector, append the first element from the above set.

Merging numbers to form a big number

If I have an int array with elements {1,2,3,4}
and I do not want to add the ints inside it but instead I want to have an int variable that holds the first 3 digits of the array for it to be int x = 123; and 123 being the first 3 elements{1,2,3} of the array, any ideas?
Basically instead of having 1 2 3 as separate digits in 3 separate indexes of the array I'd like to have 1 index OR variable that will be 123 as an actual 3 digit number.
You can use this approch. First of all assign the first digit of array (stored at array[0]) to the variable x. Then multiply it with 10 and then add the next digit of array into it, and do it one more time to insert first three digits into variable x.
Here is the code and hope it helps
#include<iostream>
int main()
{
int array[] = {1,2,3,4}, x = 0, i;
for(i=0;i<3;i++)
{
x = (x * 10) + array[i];
}
cout<<x;
return 0;
}

Query based shifting elements in array

We are given two numbers n and m. n indicates the number of elements in the array and m indicates number of queries.We are given m queries.We need to perform two types of queries on the array.Queries can be of two types, type 1 and type 2.
TYPE 1 queries are represented as (1 i j ) : Modify the given array by removing elements between i to j position and adding them to the front.
TYPE 2 queries are represented as (2 i j ) : Modify the given array by removing elements between i to j position and adding them to the back.
Our task is to simply print the difference array[1]-array[n] after the execution of queries followed by printing the array.
INPUT FORMAT:
First line consists of two space-separated integers, n and m.
Second line contains n integers, which represent the elements of the array.
m queries follow. Each line contains a query of either type 1 or type 2 in the form (type i j).
OUTPUT FORMAT:
Print the absolute value a[0]-a[n] in the first line.
Print elements of the resulting array in the second line. Each element should be separated by a single space.
EXAMPLE:
Given array is [1,2,3,4,5,6,7,8].
After execution of query(1 2 4),the array becomes(2,3,4,1,5,6,7,8).
After execution of query(2 3 5),the array becomes(2,3,6,7,8,4,1,5).
After execution of query(1 4 7),the array becomes(7,8,4,1,2,3,6,5).
After execution of query(2 1 4),the array becomes(2,3,6,5,7,8,4,1).
For the problem,I wrote a program as follows:
int main()
{
int n,m;
cin>>n;
cin>>m;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int count; // counter to control no of queries to accept
for(count=0;count<m;count++)
{
int type,start,end; // 3 parts of query
cin>>type;cin>>start;cin>>end;
if(type==1)
{
//calculated difference between (start,end) to find no of iterations
for(int i=0;i<=(start-end);i++)
{ // t is temporary variable
int t=arr[(start-1)+i]; //(start-1) as index starts from 0
arr[(start-1)+i]=arr[i];
arr[i]=t;
}
}
else
{
for(int i=0;i<=(start-end);i++)
{
int t=arr[(start-1)+i];
// elements inserted from end so we subtract (n)-(start-end)
arr[(start-1)+i]=arr[(n-1)-(start-end)+i];
arr[(n-1)-(start-end)+i]=t;
}
}
count++;
//increment count
}
int absolute=abs(arr[0]-arr[n-1]);
cout<<absolute<<"\n";
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" "<<endl;
}
return 0;
}
I was expecting the code to work correctly,but surprisngly did not even display the output correctly as well.Here is the test case:
INPUT:
8 4
1 2 3 4 5 6 7 8
1 2 4
2 3 5
1 4 7
2 1 4
EXPECTED OUTPUT:
1
2 3 6 5 7 8 4 1
MY OUTPUT:
7
1
2
3
4
5
6
7
8
I had dry run the code many times but cannot seem to understand where the problem is coming from.Please look at the code and provide me suggestions.
The for loop condition is wrong.
CORRECT WAY : for ( int i = 0; i<=(end - start ) ; i++)

Finding the smallest possible number which cannot be represented as sum of 1,2 or other numbers in the sequence

I am a newbie in C++ and need logical help in the following task.
Given a sequence of n positive integers (n < 10^6; each given integer is less than 10^6), write a program to find the smallest positive integer, which cannot be expressed as a sum of 1, 2, or more items of the given sequence (i.e. each item could be taken 0 or 1 times). Examples: input: 2 3 4, output: 1; input: 1 2 6, output: 4
I cannot seem to construct the logic out of it, why the last output is 4 and how to implement it in C++, any help is greatly appreciated.
Here is my code so far:
#include<iostream>
using namespace std;
const int SIZE = 3;
int main()
{
//Lowest integer by default
int IntLowest = 1;
int x = 0;
//Our sequence numbers
int seq;
int sum = 0;
int buffer[SIZE];
//Loop through array inputting sequence numbers
for (int i = 0; i < SIZE; i++)
{
cout << "Input sequence number: ";
cin >> seq;
buffer[i] = seq;
sum += buffer[i];
}
int UpperBound = sum + 1;
int a = buffer[x] + buffer[x + 1];
int b = buffer[x] + buffer[x + 2];
int c = buffer[x + 1] + buffer[x + 2];
int d = buffer[x] + buffer[x + 1] + buffer[x + 2];
for (int y = IntLowest - 1; y < UpperBound; y++)
{
//How should I proceed from here?
}
return 0;
}
What the answer of Voreno suggests is in fact solving 0-1 knapsack problem (http://en.wikipedia.org/wiki/Knapsack_problem#0.2F1_Knapsack_Problem). If you follow the link you can read how it can be done without constructing all subsets of initial set (there are too much of them, 2^n). And it would work if the constraints were a bit smaller, like 10^3.
But with n = 10^6 it still requires too much time and space. But there is no need to solve knapsack problem - we just need to find first number we can't get.
The better solution would be to sort the numbers and then iterate through them once, finding for each prefix of your array a number x, such that with that prefix you can get all numbers in interval [1..x]. The minimal number that we cannot get at this point is x + 1. When you consider the next number a[i] you have two options:
a[i] <= x + 1, then you can get all numbers up to x + a[i],
a[i] > x + 1, then you cannot get x + 1 and you have your answer.
Example:
you are given numbers 1, 4, 12, 2, 3.
You sort them (and get 1, 2, 3, 4, 12), start with x = 0, consider each element and update x the following way:
1 <= x + 1, so x = 0 + 1 = 1.
2 <= x + 1, so x = 1 + 2 = 3.
3 <= x + 1, so x = 3 + 3 = 6.
4 <= x + 1, so x = 6 + 4 = 10.
12 > x + 1, so we have found the answer and it is x + 1 = 11.
(Edit: fixed off-by-one error, added example.)
I think this can be done in O(n) time and O(log2(n)) memory complexities.
Assuming that a BSR (highest set bit index) (floor(log2(x))) implementation in O(1) is used.
Algorithm:
1 create an array of (log2(MAXINT)) buckets, 20 in case of 10^6, Each bucket contains the sum and min values (init: min = 2^(i+1)-1, sum = 0). (lazy init may be used for small n)
2 one pass over the input, storing each value in the buckets[bsr(x)].
for (x : buffer) // iterate input
buckets[bsr(x)].min = min(buckets[bsr(x)].min, x)
buckets[bsr(x)].sum += x
3 Iterate over buckets, maintaining unreachable:
int unreachable = 1 // 0 is always reachable
for(b : buckets)
if (unreachable >= b.min)
unreachable += b.sum
else
break
return unreachable
This works because, assuming we are at bucket i, lets consider the two cases:
unreachable >= b.min is true: because this bucket contains values in the range [2^i...2^(i+1)-1], this implies that 2^i <= b.min. in turn, b.min <= unreachable. therefor unreachable+b.min >= 2^(i+1). this means that all values in the bucket may be added (after adding b.min all the other values are smaller) i.e. unreachable += b.sum.
unreachable >= b.min is false: this means that b.min (the smallest number the the remaining sequence) is greater than unreachable. thus we need to return unreachable.
The output of the second input is 4 because that is the smallest positive number that cannot be expressed as a sum of 1,2 or 6 if you can take each item only 0 or 1 times. I hope this can help you understand more:
You have 3 items in that list: 1,2,6
Starting from the smallest positive integer, you start checking if that integer can be the result of the sum of 1 or more numbers of the given sequence.
1 = 1+0+0
2 = 0+2+0
3 = 1+2+0
4 cannot be expressed as a result of the sum of one of the items in the list (1,2,6). Thus 4 is the smallest positive integer which cannot be expressed as a sum of the items of that given sequence.
The last output is 4 because:
1 = 1
2 = 2
1 + 2 = 3
1 + 6 = 7
2 + 6 = 8
1 + 2 + 6 = 9
Therefore, the lowest integer that cannot be represented by any combination of your inputs (1, 2, 6) is 4.
What the question is asking:
Part 1. Find the largest possible integer that can be represented by your input numbers (ie. the sum of all the numbers you are given), that gives the upper bound
UpperBound = sum(all_your_inputs) + 1
Part 2. Find all the integers you can get, by combining the different integers you are given. Ie if you are given a, b and c as integers, find:
a + b, a + c, b + c, and a + b + c
Part 2) + the list of integers, gives you all the integers you can get using your numbers.
cycle for each integer from 1 to UpperBound
for i = 1 to UpperBound
if i not = a number in the list from point 2)
i = your smallest integer
break
This is a clumsy way of doing it, but I'm sure that with some maths it's possible to find a better way?
EDIT: Improved solution
//sort your input numbers from smallest to largest
input_numbers = sort(input_numbers)
//create a list of integers that have been tried numbers
tried_ints = //empty list
for each input in input_numbers
//build combinations of sums of this input and any of the previous inputs
//add the combinations to tried_ints, if not tried before
for 1 to input
//check whether there is a gap in tried_ints
if there_is_gap
//stop the program, return the smallest integer
//the first gap number is the smallest integer

How can I find the number of ways a number can be expressed as a sum of primes? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Generating the partitions of a number
Prime number sum
The number 7 can be expressed in 5 ways as a sum of primes:
2 + 2 + 3
2 + 3 + 2
2 + 5
3 + 2 + 2
5 + 2
Make a program that calculates, in how many ways number n can be
expressed as a sum of primes. You can assume that n is a number
between 0-100. Your program should print the answer in less than a
second
Example 1:
Give number: 7 Result: 5
Example 2:
Give number: 20 Result: 732
Example 3:
Give number: 80 Result: 10343662267187
I've been at this problem for hours. I can't figure out how to get n from (n-1).
Here are the sums from the first 30 numbers by a tree search
0 0 0 1 2 2 5 6 10 16 19 35 45 72 105 152 231 332 500 732 1081 1604 2351 3493 5136 7595 11212 16534 24441
I thought I had something with finding the biggest chain 7 = 5+2 and somehow using the knowledge that five can be written as 5, 3+2, 2+3, but somehow I need to account for the duplicate 2+3+2 replacement.
Look up dynamic programming, specifically Wikipedia's page and the examples there for the fibonacci sequence, and think about how you might be able to adapt that to your problem here.
Okay so this is a complicated problem. you are asking how to write code for the Partition Function; I suggest that you read up on the partition function itself first. Next you should look at algorithms to calculate partitions. It is a complex subject here is a starting point ... Partition problem is [NP complete] --- This question has already been asked and answered here and that may also help you start with algorithms.
There're several options. Since you know the number is between 0-100, there is the obvious: cheat, simply make an array and fill in the numbers.
The other way would be a loop. You'd need all the primes under 100, because a number which is smaller than 100 can't be expressed using the sum of a prime which is larger than 100. Eg. 99 can't be expressed as the sum of 2 and any prime larger than 100.
What you also know is: the maximum length of the sum for even numbers is the number divided by 2. Since 2 is the smallest prime. For odd numbers the maximum length is (number - 1) / 2.
Eg.
8 = 2 + 2 + 2 + 2, thus length of the sum is 4
9 = 2 + 2 + 2 + 3, thus length of the sum is 4
If you want performance you could cheat in another way by using GPGPU, which would significantly increase performance.
Then they're is the shuffling method. If you know 7 = 2 + 2 + 3, you know 7 = 2 + 3 + 2. To do this you'd need a method of calculating the different possibilities of shuffling. You could store the combinations of possibilities or keep them in mind while writing your loop.
Here is a relative brute force method (in Java):
int[] primes = new int[]{/* fill with primes < 100 */};
int number = 7; //Normally determined by user
int maxLength = (number % 2 == 0) ? number / 2 : (number - 1) / 2; //If even number maxLength = number / 2, if odd, maxLength = (number - 1) / 2
int possibilities = 0;
for (int i = 1; i <= maxLength; i++){
int[][] numbers = new int[i][Math.pow(primes.length, i)]; //Create an array which will hold all combinations for this length
for (int j = 0; j < Math.pow(primes.length, i); j++){ //Loop through all the possibilities
int value = 0; //Value for calculating the numbers making up the sum
for (int k = 0; k < i; k++){
numbers[k][j] = primes[(j - value) % (Math.pow(primes.length, k))]; //Setting the numbers making up the sum
value += numbers[k][j]; //Increasing the value
}
}
for (int x = 0; x < primes.length; x++){
int sum = 0;
for (int y = 0; y < i; y++){
sum += numbers[y];
if (sum > number) break; //The sum is greater than what we're trying to reach, break we've gone too far
}
if (sum == number) possibilities++;
}
}
I understand this is complicated. I will try to use an analogy. Think of it as a combination lock. You know the maximum number of wheels, which you have to try, hence the "i" loop. Next you go through each possibility ("j" loop) then you set the individual numbers ("k" loop). The code in the "k" loop is used to go from the current possibility (value of j) to the actual numbers. After you entered all combinations for this amount of wheels, you calculate if any were correct and if so, you increase the number of possibilities.
I apologize in advance if I made any errors in the code.