Given an array, I am trying to find the maximum sub-array sum. A sub-array is as follows. For example, I get the following array: [9, -7, 5, 3, 91]. Whilst [9, -7, 5] is a sub-array, [9, 5, 3, 91] is not. My code is below:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int arraylen, subarraylen, subarraysum, itervar1, itervar2, itervar3, incrementvar;
cin >> arraylen;
vector<int> mainarray(arraylen);
vector<int> sumarray(arraylen * (arraylen-1) + 1);
for (itervar1 = 0; itervar1 < arraylen; itervar1++) {
cin >> mainarray[itervar1];
}
sumarray[0] = 0;
for (itervar1 = 0; itervar1 < arraylen; itervar1++) {
for (itervar2 = arraylen; itervar2 > 0; itervar2--) {
subarraylen = itervar2-itervar1;
if (subarraylen < 1) {
continue;
}
vector<int> subarray(subarraylen);
incrementvar = 0;
for (itervar3 = itervar1; itervar3 < itervar2; itervar3++) {
subarray[incrementvar] = mainarray[itervar3];
incrementvar++;
}
subarraysum = 0;
for (itervar3 = 0; itervar3 < subarraylen; itervar3++) {
subarraysum += subarray[itervar3];
}
}
}
return 0;
}
For some reason, it doesn't work; just infinitely loops around. Any help would be appreciated.
First, here is a routine to list all the sub arrays:
vector<int> vec{ 9, -7, 5, 3, 91 };
int sz = vec.size();
for(int start = 0; start < sz; start++)
{
for(int end = start; end < sz; end++)
{
for(int j = start; j <= end; j++)
{
cout << vec[j] << ", ";
}
cout << "\n";
}
}
Now you just have to get the total in loop j, add to a vector sum. You don't need to know the size of sum before hand. Use push_back to add total to sum.
Note, the array itself is included as a sub array, you can exclude that array depending on what the definition is.
Related
Question: Find unique elements from the given array and print them
I have dry run below given code many times but i am not getting what is the problem in the code.
#include <iostream>
using namespace std;
void findingUniqueElement(int array[], int size)
{
int brray[100];
int count = 0;
bool equal = 0;
for (int i = 0; i < size; i++)
{
equal = 0;
int value = array[i];
for (int j = 0; j < size; j++)
{
if (i != j && value == array[j])
{
equal = 1;
break;
}
}
if (equal == 0)
{
brray[i] = value;
count++;
}
}
for (int i = 0; i < count; i++)
{
cout << brray[i] << " ";
}
}
int main()
{
int arr[6] = {1, 2, 2, 5, 3, 7};
findingUniqueElement(arr, 6);
}
i was expecting as an output
1 5 3 7
but when i run the code, getting as output
1 1877357483 1878039440 5
Welcome to SO! Here is the code modified by me:
#include <cstring>
#include <iostream>
using namespace std;
void findingUniqueElement(int array[], int size) {
int brray[100];
memset(brray, 0, 100); // modified here
int count = 0;
bool equal = 0;
for (int i = 0; i < size; i++) {
equal = 0;
int value = array[i];
for (int j = 0; j < size; j++) {
if (i != j && value == array[j]) {
equal = 1;
break;
}
}
if (equal == 0) {
brray[i] = value;
count++;
}
}
for (int i = 0; i < size; i++) { // modified here
if (brray[i] != 0) // modified here
cout << brray[i] << " ";
}
}
int main() {
int arr[6] = {1, 2, 2, 5, 3, 7};
findingUniqueElement(arr, 6);
}
I modified three places in your code:
You should initialize brray when you declare it, the strange values output are because they were in the memory when you defined brray, you should clean the memory before you use it.
The way you store unique number in brray is not very correct, when array[i] is not unique, you will add i, which leave 0 at brray[i], so to fit your code, you should make i from 0 to size. To get more clear about what I'm talking about, you can check the memory of brray.
Since I assume there is no 0 in your test data, so if there is a 0 in barray, you know it is not a valid value, just skip it. Also, you can use a more elegant way to do this, like #Anand Sowmithiran commented:
int brray[100];
memset(brray, 0, 100);
int count = 0;
for (/* conditions... */) {
// if there is a unique number
brray[count++] = unique_number;
}
for (int index = 0; index < count; index++) {
cout << brray[index] << " ";
}
Hope my answer is helpful!
i'm trying to make it so if i enter the number 3 , the matrix would change to {1,2,4,5,6,7,8,9,10,11,12,0}, i'm not sure if the method of switching the element between two arrays is the best way to do it and i'm trying to do it using pointers
using namespace std;
#include <iomanip>
int main() {
int arr[3][4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, i, j,c;
int* ptr = &arr[0][0];
int zero[3][4] = { 0,0,0,0,0,0,0,0,0,0,0,0 };
int* zptr = &zero [0][0];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
cout << setw(8) << arr[i][j] << ' ';
}
cout << endl;
cout << ' ' << endl;
}
for (i = 0; i < 3; i++) {
if (arr[i][0] = i)
{
break;
}
for (int j = 0; j < 4; j++)
cin >> i;
cout << ptr;
}
return 0;
}
you could use easier approach to achieve this using vector in c++ and by finding the index of the input element, consider this example :
int getIndex(vector<int> v, int K) {
auto it = find(v.begin(), v.end(), K);
// calculating the index of K
// note that here i'm supposed the input is valid
int index = it - v.begin();
return index;
}
and you can use the index you get to 1) append in A the element B[index], 2) assign B[index] to A[index] and 3) erase the element A[index].
hope this can be helpful.
I wrote the below code for merge sort but it's not working, And I am unable to find out problem!
Every time the output becomes same as input, I think that problem may occur due to vector reference.
I think mergeSort is not creating a new vector for sub array. But I am still confused.
input vector: 5, 4, 3, 2, 1
output: 5, 4, 3, 2, 1
Req output: 1, 2, 3, 4, 5
#include <iostream>
#include <vector>
using namespace std;
void merge(vector<int> &la, vector<int> &ra, vector<int> &A) {
int i = 0, j = 0, k = 0;
// overwriting A using its solved sub arrays i.e la, ra
while (i < la.size() && j < ra.size()) {
if (la[i] <= ra[j]) {
A[k] = la[i];
i++;
k++;
} else {
A[k] = ra[j];
j++;
k++;
}
}
// if any subarray left then
while (i < la.size()) {
A[k] = la[i];
k++;
i++;
}
while (j < ra.size()) {
A[k] = ra[j];
k++;
j++;
}
}
mergeSort function:
void mergeSort(vector<int> &A) {
if (A.size() < 2)
return;
int len = A.size();
vector<int> la, ra;
for (int i = 0; i < len / 2; i++)
la.push_back(A[i]);
for (int i = len / 2; i < len; i++)
ra.push_back(A[i]);
// dividing the proble into subproblem
mergeSort(la);
mergeSort(ra);
// merging the solved subproblem
merge(la, ra, A);
}
Driver function:
int main(void) {
int arr[] = { 5, 4, 3, 2, 1 };
vector<int> A(arr, arr + 5);
for (int i = 0; i < A.size(); i++)
cout << A[i] << " ";
cout << endl;
mergeSort(A);
for (int i = 0; i < A.size(); i++)
cout << A[i] << " ";
return 0;
}
The code posted does not seem to have a problem.
Executing it produces the expected output: 1 2 3 4 5, so there is something else going on that could cause your observations: you might be running an executable produced by a previous or at least different version of the code.
I was tinkering with C++ and I was like let's make a sorting algorithm :)
I did something, but it didn't sort the array but instead the array was overwritten with the max number
I don't know where is my mistake because I ran the algorithm on paper (don't ask) and it was correct.
I tried every modification possible.
any help?
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int mn = 0, mx = 0;
int a[] = { 4, 8, 5, 2, 6, 9, 0, 3, 1, 7 };
for (int i = 0; i < 10; i++)
{
mn = a[i]; mx = a[i];
for (int j = i; j < 10 - i; j++)
{
mn = min(a[j], mn);
mx = max(a[j], mx);
}
swap(a[i], mn);
swap(a[10-1-i], mx);
}
for(int i=0;i<10;i++)
{
cout<<a[i]<<" ";
}
}
You are not swapping array elements, but basically you write the min/max values to the corresponding places within the array. Their old value is simply overwritten. You need to track the positions of the min/max elements and swap accordingly, e.g. swap(a[i], a[min_pos]). Additionally, you could run your outer loop up until the middle of the array is reached as you put two elements into their place on each iteration.
Here's the working code:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int mn = 0, mx = 0;
int a[] = { 4, 8, 5, 2, 6, 9, 0, 3, 1, 7 };
for (int i = 0; i < 10 / 2; i++)
{
int min_pos = i, max_pos = i;
for (int j = i; j < 10 - i; j++)
{
if (a[j] < a[min_pos]) {
min_pos = j;
} else if (a[j] > a[max_pos]) {
max_pos = j;
}
}
int min_val = a[min_pos];
int max_val = a[max_pos];
swap(a[i], a[min_pos]);
swap(a[10-1-i], a[max_pos]);
a[i] = min_val;
a[10-1-i] = max_val;
}
for(int i=0;i<10;i++)
{
cout<<a[i]<<" ";
}
}
Note, you need to take care of 'special cases', e.g. when the min_pos and max_pos are at the ends of the interval - they would be swapped twice staying in their original positions.
I've been tinkering around with it for a while now and I'm so close! Now the output seems to be continuously printing a zero as the first value of the "sorted" vector. This is homework on how to create a selection sort in C++.
Example Output
Vector: 6, 2, 11, 1, 12, 4
Sorted Vector: 0, 2, 11, 6, 12, 4
Code
void selectionSort (vector<int>& data)
{
int min, temp, n=data.size(), i, j;
for (i=0; i<n; i++)
{
min = i;
for (j=i+1; j<n; j++)
{
if (data[min]>data[j])
{
min=j;
}
temp=data[min];
data[min]=data[i];
data[i]=temp;
}
return;
}
}
int main()
{
int n;
vector<int> data;
cout<<"Vector length?: "<<endl;
cin>>n;
srand(time(0));
for (int i=0; i<n; i++)
{
data.push_back(rand()%20+1);
}
cout<<"Vector: "<<endl;
for (int i=0; i<n; i++)
{
cout<<data[i]<<" "<<endl;
}
selectionSort(data);
cout<<"Selection Sorted Vector: "<<endl;
for (int i=0; i<data.size(); i++)
{
cout<<data[i]<<" "<<endl;
}
system("Pause");
return 0;
}
Consider the following correct implementation of a selection sort and compare it to yours:
#include <iostream>
#include <vector>
void selection_sort(std::vector<int> &numbers)
{
// Iterate through all possible start indices.
for (int i = 0; i < numbers.size(); ++i)
{
// Determine the index of the minimum for this iteration.
int index_of_min = i;
for (int j = i; j < numbers.size(); ++j)
{
if (numbers[j] < numbers[index_of_min])
{
index_of_min = j;
}
}
// Swap the minimum element with the element at the start index.
int temp = numbers[i];
numbers[i] = numbers[index_of_min];
numbers[index_of_min] = temp;
}
}
int main()
{
std::vector<int> numbers = { 20, 17, 13, 12, 25 };
selection_sort(numbers);
for (size_t i = 0; i < numbers.size(); ++i)
{
std::cout << numbers[i] << " ";
}
}
Given an array of n elements, a selection sort performs n swaps.
You're performing far more swaps than that.
You also have an unexpectedly early call to return.
Let's look at a proper implementation of the sort:
#include <iostream>
#include <vector>
using namespace std;
void selectionSort (vector<int>& data)
{
const int n = data.size();
for (int i=0; i<n; i++)
{
int min = i;
for (int j=i+1; j<n; j++)
if (data[min]>data[j])
min = j;
swap(data[min], data[i]);
}
}
int main() {
vector<int> data = {6, 2, 11, 1, 12, 4};
selectionSort(data);
for (auto element : data)
cout << element << " ";
cout << "\n";
}
Which outputs:
1 2 4 6 11 12