I am suppose to swap an array with the odds in one array and the evens in another while keeping track of the count and the values being swapped.
{2, 3, 6}
{1, 4, 7}
will become
{1, 3, 7}
{2, 4, 6}
With 2 swaps, and the values being swapped are
1 &2, 6 & 7.
int main() {
int a1[3] = { 2, 3, 6 };
int a2[3] = { 1, 4, 7 };
int i;
int swapcount = 0;
int swapvalue;
std::cout << "Before swap:\n" << endl;
std::cout << "Array 1:\n" << endl;
for (int i = 0; i < 3; i++) {
cout << " " << a1[i] << endl;
}
std::cout << "Array 2:\n" << endl;
for (int i = 0; i < 3; i++) {
std::cout << " " << a2[i] << endl;
}
for (int i = 0; i < 3; i++) {
if (a1[i] % 2 != 1) {
swapcount++;
int temp = a1[i];
a1[i] = a2[i];
a2[i] = temp;
swapvalue = i;
}
}
std::cout << "After swap:\n" << endl;
std::cout << "Array 1:\n" << endl;
for (int i = 0; i < 3; i++) {
std::cout << " " << a1[i] << endl;
}
std::cout << "Array 2:\n" << endl;
for (int i = 0; i < 3; i++) {
std::cout << " " << a2[i] << endl;
}
std::cout << "swap count: " << swapcount << endl;
std::cout << "swap value: " << swapvalue << endl;
}
So far, I have gotten the swap and counter to work but I cannot seem to figure out:
How to find and store the individual values of the elements that are swapped? (I can get only one value to show.)
Can I get any hints on how to all grab the values? I am not allowed to use any additional libraries except for the input and output streams. Thanks ahead of time.
Create an auxiliary array swapbool, set boolean = 1 if a swap is done.
#include<iostream>
using namespace std;
int main() {
int a1[3] = { 2, 3, 6 };
int a2[3] = { 1, 4, 7 };
int swapbool[3] = {0,0,0};
int i;
int swapcount = 0;
int swapvalue;
std::cout << "Before swap:\n" << endl;
std::cout << "Array 1:\n" << endl;
for (int i = 0; i < 3; i++) {
cout << " " << a1[i] << endl;
}
std::cout << "Array 2:\n" << endl;
for (int i = 0; i < 3; i++) {
std::cout << " " << a2[i] << endl;
}
for (int i = 0; i < 3; i++) {
if (a1[i] % 2 != 1) {
swapcount++;
int temp = a1[i];
a1[i] = a2[i];
a2[i] = temp;
// swapvalue = i;
swapbool[i]=1;
}
}
std::cout << "After swap:\n" << endl;
std::cout << "Array 1:\n" << endl;
for (int i = 0; i < 3; i++) {
std::cout << " " << a1[i] << endl;
}
std::cout << "Array 2:\n" << endl;
for (int i = 0; i < 3; i++) {
std::cout << " " << a2[i] << endl;
}
std::cout << "swap count: " << swapcount << endl;
for (int i = 0; i < 3; i++) {
if(swapbool[i] == 1)
{
std::cout << "swapvalue1-> " << a2[i] << endl;
std::cout << "swapvalue2-> " << a1[i] << endl;
}
}
//std::cout << "swap value: " << swapvalue << endl;
}
There are a lot of ways of doing it. The simplest solution is to store them in std::vector of std::pair:
std::vector<std::pair<int, int>> swapvalues;
And then inserting:
swapvalues.emplace_back(val1, val2);
By the way, in your code you store index, not values. If you want to store indices, use only std::vector of integers.
How to find the individual values of the elements that are swapped?
When you swap the elements store their indexes:
int swappedValuesIndex[];
for (int i = 0; i < 3; i++) {
if (a1[i] % 2 != 1) {
// store swapped values' index
swappedValuesIndex[swapcount] = i;
swapcount++;
int temp = a1[i];
a1[i] = a2[i];
a2[i] = temp;
swapvalue = i;
}
}
// print swapped values
for (int i = 0; i < swapcount; i++){
cout <<"a1["<< swappedValuesIndex[i] <<"]"<< a1[swappedValuesIndex[i]] <<'\n';
cout <<"a2["<< swappedValuesIndex[i] <<"]"<< a2[swappedValuesIndex[i]] <<'\n';
}
Related
I'm trying to write a function which sort an array and I met a problem. When I sort an array it always return 0 in first position of sorted array. No matter what combination it is.
void sorting(int wielkosc)
{
int t[wielkosc];
//filling
for (int i = 0; i < wielkosc; i++)
{
t[i] = rand()% 100 + 1;
}
// before sort
cout << "before sorting: " << endl;
for (int i = 0; i < wielkosc; i++)
{
cout << "[" << i << "] -> " << t[i] << endl;
}
cout << endl;
// asc...
int iTemp = 0;
for (int i = 0; i < wielkosc; i++)
{
for (int j = i + 1; j <= wielkosc; j++)
{
//jak chcesz zmienic na malejaco to se przekrec '<' na '>'
if (t[j] < t[i])
{
iTemp = t[i];
t[i] = t[j];
t[j] = iTemp;
}}}
// after sorting
cout << "after sorting: " << endl;
for (int i = 0; i < wielkosc; i++)
{
cout << "[" << i << "] -> " << t[i] << endl;
}
cout << endl;
}
void adde(int& v, char array[5])
{
if (v > 5) {
v = -1;
}
for (int k = 0; k < 5; k++) {
if (array[k] == 'C') {
array[k] = '-';
}
}
v++;
array[v] = 'C';
}
this is my function
int mov = -1;
char item[5];
for (int i = 0; i < 5; i++) {
item[i] = '-';
}
cout << "Initially " << endl;
for (int i = 0; i < 5; i++) {
cout << "[" << i + 1 << " ] ";
}
cout << endl;
for (int j = 0; j < 5; j++) {
cout << item[j] << " ";
}
cout << endl;
cout << "After Item 1, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
cout << item[j] << " ";
}
cout << endl;
cout << "After Item 2, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
cout << item[j] << " ";
}
cout << endl;
cout << "After Item 3, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
cout << item[j] << " ";
}
cout << endl;
cout << "After Item 4, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
cout << item[j] << " ";
}
cout << endl;
cout << "After Item 5, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
cout << item[j] << " ";
}
cout << endl;
My code works fine till here.
After the last item i want my cursor to point back to first index
but shows weird Library Run time error
After it runs this highlighted part of code
cout << "After Item 6, " << endl;
adde(mov, item);
for (int j = 0; j < 5; j++) { cout << item[j] << " "; } }
Heading ##You did a simple mistake. No need for a debbugger here. Arrays in C/C++ start with index 0. So if you have an array of size 5, like in your example char item[5];, the valid indices are 0,1,2,3,4. But not 5.
In your function adde you simply have the wrong boundary check. In your very first statement you have written:
if (v > 5) {
then later
v++;
array[v] = 'C';
So, if v is >3, for example 4 or 5, you will increment it and access array[5] or array[6], which is out of bounds and produces an error.
You may simply correct it and use
if (v > 3) {
as you first statement. This will fix the problem:
#include <iostream>
void adde(int& v, char array[5])
{
if (v > 3) {
v = -1;
}
for (int k = 0; k < 5; k++) {
if (array[k] == 'C') {
array[k] = '-';
}
}
v++;
array[v] = 'C';
}
int main() {
int mov = -1;
char item[5];
for (int i = 0; i < 5; i++) {
item[i] = '-';
}
std::cout << "Initially " << std::endl;
for (int i = 0; i < 5; i++) {
std::cout << "[" << i + 1 << " ] ";
}
std::cout << std::endl;
for (int j = 0; j < 5; j++) {
std::cout << item[j] << " ";
}
std::cout << std::endl;
std::cout << "After Item 1, " << std::endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
std::cout << item[j] << " ";
}
std::cout << std::endl;
std::cout << "After Item 2, " << std::endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
std::cout << item[j] << " ";
}
std::cout << std::endl;
std::cout << "After Item 3, " << std::endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
std::cout << item[j] << " ";
}
std::cout << std::endl;
std::cout << "After Item 4, " << std::endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
std::cout << item[j] << " ";
}
std::cout << std::endl;
std::cout << "After Item 5, " << std::endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
std::cout << item[j] << " ";
}
std::cout << std::endl;
std::cout << "After Item 6, " << std::endl;
adde(mov, item);
for (int j = 0; j < 5; j++) {
std::cout << item[j] << " ";
}
std::cout << std::endl;
return 0;
}
Please additionally note:
The design is not very good. Please do not use C-style arrays in C++. Please avoid pointer decays in calls to functions. Please rethink you complete design. I can see, what you are doing. This can be done easier in C++, but for a really good or approriate solution, we need to know the requriements.
I have a function that returns a pointer to an array, and I want to print each value in the array
When I run it, it prints
int* merge_sort(int arr[], int size) {
if (size <= 1) {
return &arr[0];
}
int size1 = size/2;
int arr1[size1];
for (int i = 0; i < size1; i++) {
arr1[i] = arr[i];
}
int size2 = size-size1;
int arr2[size2];
for (int i = 0; i < (size2); i++) {
arr2[i] = arr[i+size1];
}
int p1 = 0;
int p2 = 0;
int sorted[size];
while (p1 < size1 && p2 < size2) {
if (arr1[p1] < arr2[p2]) {
sorted[p1+p2] = arr1[p1];
p1++;
} else {
sorted[p1+p2] = arr2[p2];
p2++;
}
}
while (p1 < size1) {
sorted[p1+p2] = arr1[p1];
p1++;
}
while (p2 < size2) {
sorted[p1+p2] = arr2[p2];
p2++;
}
cerr << "sorted: ";
for (int& i : sorted) {
cerr << i << ",";
}
cerr << endl;
return &sorted[0];
}
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int N;
int horses[N];
cin >> N; cin.ignore();
for (int i = 0; i < N; i++) {
int Pi;
cin >> Pi; cin.ignore();
horses[i] = Pi;
}
int *sorted = merge_sort(horses, N);
cerr << "~ " << sorted[0] << " " << sorted[1] << " " << sorted[2] << endl;
//cerr << "~~ " << sorted << " " << *sorted << " " << endl;
cerr << "^ " << *(sorted + 0) << endl;
cerr << "^ " << *(sorted + 1) << endl;
cerr << "^ " << *(sorted + 2) << endl;
for (int i = 0; i < N; i++) {
//cerr << "i " << i << endl;
// cerr << "SORTED?? " << sorted[i] << endl;
cerr << "value: " << *(sorted + i) << " ";
//cerr << "*** " << *(sorted) + i << endl;
}
cerr << endl;
}
When I run it, it prints
sorted: 5,8,9,
~ 5 8 9
^ -5728
^ 942815029
^ 6297320
value: 959592096 value: 0 value: -157570874
Why is my for loop not printing the values "5, 8, 9"? How can I fix it so that it does?
(Edited to be more detailed. Also, I realize my merge sort is wrong but I'm just trying to get it to return something I can use right now ^.^)
Make sure that you returned correct pointer, for example (if pointer should point to values):
std::cerr << "\n" << sorted << " "<< &values << "\n";
should return same values:
003DFD64 003DFD64
Seems ok. Check your sort function
cpp.sh/4rrk
// Example program
#include <iostream>
#include <algorithm>
const size_t N = 3;
int* sort(int arr[]) {
// Sort arr and it should be equal to [5, 7, 8]
std::sort(arr, arr+N);
return arr;
}
int main() {
int values[N];
values[0] = 7;
values[1] = 5;
values[2] = 8;
for (size_t i = 0; i < N; ++i) {
std::cout << *(values + i) << " ";
}
std::cout << std::endl << values[0] << " " << values[1] << " " << values[2] << std::endl;
int *sorted = sort(values);
std::cout << "It is same arrays: " << values << " " << sorted << std::endl;
for (size_t i = 0; i < N; ++i) {
std::cout << *(sorted + i) << " ";
}
std::cout << std::endl << sorted[0] << " " << sorted[1] << " " << sorted[2] << std::endl;
return 0;
}
Output:
7 5 8
7 5 8
It is same arrays: 0x7329bfdc1d90 0x7329bfdc1d90
5 7 8
5 7 8
int number1=5;
int number2=4;
for(int i=1; i<=7; i++)
{
if(rows <= 1)
for(int i=1; i<=7; i++)
{
cout<< number1;
}
else if(i<7)
{
cout<< endl;
for(int j=1; j<=6; j++)
{
if(side2==1 || side2==6)
cout<< number1;
else
cout<< " ";
}
}
else
{
cout<< endl;
for(int k=1; k<=6; k++)
{
cout<<number1;
}
}
My program prints this shape
555555555
5 5
5 5
5 5
5 5
555555555
but I have been trying to make it look like this
555555555
544444445
543333345
543222345
543212345
543222345
543333345
544444445
555555555
I have heard about this website from a friend how much helpful you guys are, I wish you would help me too.
The simplest would be:
std::cout << "555555555" << std::endl;
std::cout << "544444445" << std::endl;
std::cout << "543333345" << std::endl;
std::cout << "543222345" << std::endl;
std::cout << "543212345" << std::endl;
std::cout << "543222345" << std::endl;
std::cout << "543333345" << std::endl;
std::cout << "544444445" << std::endl;
std::cout << "555555555" << std::endl;
and with a loop:
for (int y = 0; y < 9; ++y) {
for (int x = 0; x < 9; ++x) {
std::cout << char('1' + std::max(std::abs(x - 4), std::abs(y - 4)));
}
std::cout << std::endl;
}
I'm a C++ novice and my problem is that I somehow (seemingly) lose vector elements just by calling .size(). For the following code segment (full code attached below) I get the following output:
A: number of elements: 560
B: number of elements: 560
B: number of elements: 0
B: number of elements: 0
B: number of elements: 0
C: number of elements: 0
//SEGMENT IN QUESTION
cout << "A: number of elements: " << combinations.size() << endl;
float sum_vect[120][2];
for (int i = 0; i < combinations.size(); ++i) {
for (int j = 0; j < 2; ++j) {
sum_vect[i][j] = 0;
}
}
cout << "B: number of elements: " << combinations.size() << endl;
cout << "B: number of elements: " << combinations.size() << endl;
cout << "B: number of elements: " << combinations.size() << endl;
cout << "B: number of elements: " << combinations.size() << endl;
for (int i = 0; i < combinations.size(); ++i) {
combination = combinations.at(i);
for (int j = 0; j < order; ++j) {
sum_vect[i][0] += (float)virtual_pos[combination[j]][0];
sum_vect[i][1] += (float)virtual_pos[combination[j]][1];
}
}
vector<int> optimal_ind;
cout << "C: number of elements: " << combinations.size() << endl;
//AUXILIARY FUNCTIONS
void nchoosek_helper(int offset, int n, int k, vector<vector<int>> &combinations, vector<int> combination) {
if (k == 0) {
combinations.push_back(combination);
return;
}
for (int i = offset; i <= n - k; ++i) {
combination.push_back(i);
nchoosek_helper(i+1, n, k-1, combinations, combination);
combination.pop_back();
}
}
double euclidean_norm(double dist1, double dist2){
return sqrt(pow(dist1,2) + pow(dist2,2));
}
//FUNCTION IN QUESTION STARTS HERE
//weirdest: look at A B C
vector<vector<char> > step37::CUDADriver::get_access_pattern(int order){
vector<vector<char> > result;
vector<vector<int> > combinations;
vector<int> combination;
nchoosek_helper(0, 16 ,order, combinations, combination);
cout << "number of combinations: " << combination.size() << endl;
// //mapping lexical index 1-16 to 2D array
int virtual_pos [16][2];
for (int i = 0; i < 16; ++i) {
virtual_pos[i][0] = i%4 * order; //write x
virtual_pos[i][1] = (int)ceil(i/4) * order; //write y
cout << "mapping " << i << "to (" << i%4 * order << "'" << (int)ceil(i/4) * order<< ")" << endl;
}
cout << "A: number of elements: " << combinations.size() << endl;
float sum_vect[120][2];
for (int i = 0; i < combinations.size(); ++i) {
for (int j = 0; j < 2; ++j) {
sum_vect[i][j] = 0;
}
}
cout << "B: number of elements: " << combinations.size() << endl;
cout << "B: number of elements: " << combinations.size() << endl;
cout << "B: number of elements: " << combinations.size() << endl;
cout << "B: number of elements: " << combinations.size() << endl;
for (int i = 0; i < combinations.size(); ++i) {
combination = combinations.at(i);
for (int j = 0; j < order; ++j) {
sum_vect[i][0] += (float)virtual_pos[combination[j]][0];
sum_vect[i][1] += (float)virtual_pos[combination[j]][1];
}
}
vector<int> optimal_ind;
cout << "C: number of elements: " << combinations.size() << endl;
cout << "main loop"<< endl;
for (int i = order; i < order*2; ++i) {
for (int j = order; j < order*2; ++j) {
int pos [2];
// pos[0] = i;
// pos[1] = j;
pos[0] = j;
pos[1] = i;
cout << "current position: (" << j << "," << i << ")" << endl;
float min_len = std::numeric_limits<float>::infinity(); //minimum length of combined vector
float min_sum_ind = std::numeric_limits<float>::infinity(); //minimum sum of individual vectors
int min_idx = -1;
for (int k = 0; k < combinations.size(); ++k) {
int curr_vect [2];
curr_vect[0] = sum_vect[k][0] - pos[0] * order;
curr_vect[1] = sum_vect[k][1] - pos[1] * order;
float curr_len = euclidean_norm(curr_vect[0], curr_vect[1]);
float min_sum_tmp = 0;
combination = combinations[k];
for (int l = 0; l < order; ++l) {
min_sum_tmp += euclidean_norm(virtual_pos[combination.at(l)][0] - pos[0],
virtual_pos[combination.at(l)][1]- pos[1]);
}
if (i==4&&j==4){
cout << " ind sum: " << min_sum_tmp << " len: " << curr_len << " sv: (" << sum_vect[k][0] << "," << sum_vect[k][1] <<
") cv: (" << curr_vect[0] << "," << curr_vect[1] << ")" <<endl;
}
if (min_len > curr_len ||
min_len == curr_len && min_sum_tmp < min_sum_ind){
min_len = curr_len;
min_idx = k;
min_sum_ind = min_sum_tmp;
}
}
// cout <<
cout << "pushing minimal idx " << min_idx << endl;
optimal_ind.push_back(min_idx);
}
}
cout << "main loop done"<< endl;
//unpack optimal combinations into relative movements
vector<char> optimal_x((int)pow(order,3));
vector<char> optimal_y((int)pow(order,3));
cout << "number of elements: " << combinations.size() << endl;
for (int i = 0; i <(int)pow(order,2); ++i) {
cout << "optimal idx: " << optimal_ind.at(i) << endl;
combination = combinations.at(optimal_ind.at(i));
for (int j = 0; j < order; ++j) {
int lex_idx = combination.at(j); //some index between 0 and 15 from 4x4 grid
//mvt range in grid relative to thread position: -1 to +
int relative_x = -1 + lex_idx % 4;
int relative_y = -1 + (int) floor(lex_idx / 4);
optimal_x[i * order + j] = relative_x;
optimal_y[i * order + j] = relative_y;
}
}
//DEBUG print
for (int i = 0; i < (int)pow(order,2); ++i) {
combination = combinations.at(optimal_ind.at(i));
cout << "combination: " << i << " ";
for (int j = 0; j < order; ++j) {
cout << combination.at(j) << " ";
}
cout << endl;
}
result.push_back(optimal_x);
result.push_back(optimal_y);
for (int i = 0; i < optimal_x.size(); ++i) {
cout << (int)optimal_x.at(i) << " " << endl;
}
cout << "optimal sizes: " << optimal_x.size() << endl;
cout << "optimal sizes: " << optimal_y.size() << endl;
cout << "result size: " << result.size() << endl;
return result;
}
I really don't understand how it's possible for a function like .size() to change the vector object (or maybe it just happens coincidentally at the same time). The application runs in single thread but I guess it wouldn't matter anyways given that everything relevant should be contained within the scope of the function. Obviously, the code stops working at a later point when I actually try to access some elements of combinations (std::out_of_range). I guess I must be missing out on something very basic given the gravity of the error. What's disturbing is that everything works just fine if I use 2 as an argument to get_access_pattern(). Everything above (tested with 3 and 4) results in this error.
You have a buffer overrun. Your output:
A: number of elements: 560
Your code:
cout << "A: number of elements: " << combinations.size() << endl;
float sum_vect[120][2];
for (int i = 0; i < combinations.size(); ++i) {
for (int j = 0; j < 2; ++j) {
sum_vect[i][j] = 0;
}
}
Look at the "i" variable when it gets to 120 in that loop. You are accessing sum_vect[120][j], which is out-of-bounds.
When a buffer overrun occurs, your program then will exhibit undefined behavior.