after reading inputs to an array:
int * inputs;
the "inputs" is 1 dimensional array: inputs[6], then reading this array out, the values are:
inputs[0]=1
inputs[1]=2
inputs[2]=3
inputs[3]=4
inputs[4]=5
inputs[5]=6
I would like to read this array into another one dimensional array:
int counter=0;
int * allElements = new int[6];
for(int i=0; i<6; i++)
{
allElements[counter++] = inputs[i];
}
That is a traditional way of reading all of the elements into one dimensional array and I believe if I read the elements of "allElements" this way:
for(int i=0; i<6; i++)
printf("%d ", allElements[i]);
and it should be: 1 2 3 4 5 6
However, I would like to read all elements of that array into the 1 dimensional array such that when I do it like this:
for(int i=0; i<6; i++)
printf("%d ", allElements[i]);
It should be: 1 3 5 2 4 6
How can I achieve this way?
int * allElements = new int[6];
for(int i=0; i<6; i+=2)
{
allElements[i/2] = inputs[i];
allElements[3+i/2] = inputs[i+1];
}
What about:
for(int i=0; i<6; i++)
{
allElements[i] = inputs[2*(i%3) + (i/3)];
}
Imagine inputs is a two-dimension array, of 3x2, then i%3 is one coordinate and i/3 the other. Just transpose it into a 2x3 matrix, and done!
const int size =6;
int inputs[size]={1,2,3,4,5,6};
int allElements[size];
...
if (size % 2)
{
int middle=(size/2) +1;
for(int i=0; i<size; i+=2)
{
allElements[i/2] = inputs[i];
if (i < size-2)
allElements[middle+i/2] = inputs[i+1];
}
}
else
{
int middle=size/2;
for(int i=0; i<size; i+=2)
{
allElements[i/2] = inputs[i];
allElements[middle+i/2] = inputs[i+1];
}
}
Logic can definitely be simplified. Just first attempt and left it alone.
If want it to work for the 1 case
allElements[0]=inputs[0];
allElements[1]=inputs[2];
allElements[2]=inputs[4];
allElements[3]=inputs[1];
allElements[4]=inputs[3];
allElements[5]=inputs[5];
Related
I'm working with c++ arrays and I found a problem. I can easily do the exercise using cin and filling array with for loop. But when I try to do it as filled array I got the error with too many initializer values. How to solve it?
#include <iostream>
using namespace std;
void func(int **arr, int row, int col)
{
for (int i=0; i<row; i++)
{
for(int j=0 ; j<col; j++)
{
cout<<arr[i][j]<<" ";
}
printf("\n");
}
}
int main()
{
int row = 2;
int colum = 2;
int** arr = new int*[row];
for(int i=0; i<row; i++)
{
arr[i] = new int[colum];
}
arr = {
{1,2},
{3,4}};
func(arr, row, colum);
return 0;
}
arr is a pointer
int** arr = new int*[row];
So it may be initialized with a braced list containing only one (assignment) expression.
For the allocated array of two elements you could write for example
int** arr = new int*[row];
for(int i=0; i<row; i++)
{
if ( i == 0 ) arr[i] = new int[colum] { 1, 2 };
else arr[i] = new int[colum] { 3, 4 };
}
or
int** arr = new int*[row];
for(int i=0, value = 1; i<row; i++)
{
arr[i] = new int[colum] { value++, value++ };
}
Pay attention to that you will need to free the dynamically allocated memory for the arrays.
Otherwise use the standard container std::vector<std::vector<int>> instead of the allocated dynamically arrays.
gfg https://practice.geeksforgeeks.org/problems/subset-sum-problem2014/1
leetcode
https://leetcode.com/problems/partition-equal-subset-sum/
Problem:
Given an array arr[] of size N, check if it can be partitioned into two parts such that the sum of elements in both parts is the same.
Example
Input: N = 4
arr = {1, 5, 11, 5}
Output: YES
Explaination:
The two parts are {1, 5, 5} and {11}.
class Solution{
public:
static int equalPartition(int N, int arr[])
{
int sum = 0;
for (int i=0; i<N; i++)
sum += arr[i];
if (sum % 2 != 0)
return 0;
sum = sum/2;
int row = N+1;
int col = sum+1;
int dp[row][col];
for (int i=0; i<col; i++)
dp[0][i] = 0;
for (int i=0; i<row; i++)
dp[i][0] = 1;
for (int i=1; i<row; i++) {
for (int j=1; j<col; j++) {
if ( j< arr[i-1])
dp[i][j] = dp[i-1][j];
else{
if(j-arr[i-1] > 0){
dp[i][j] =max(dp[i-1][j], dp[i-1][j-arr[i-1]]);
}
else{
dp[i][j] = dp[i-1][j];
}
}
}
}
return dp[row-1][col-1];
}
};
So I signed up to portal out of curiosity to figure whats wrong. I was able to get correct answer with the following code. The code makes slight changes, mostly space compression.
As I suspected, the constraints for N (100) and sum of values in array (1e5) were very critical leading to segmentation fault.
Also instead of j-arr[i-1] > 0, it should be j-arr[i-1] >= 0.
Explanation of space compression:
We only need i-1 th state to compute values of current state i, so 2 arrays of size sum each are enough. I keep a reference curr to remember which of the 2 array is to be considered current and curr^1 would be the previous array. We can further optimize to only single array of size sum, but it is out of scope of the answer.
int equalPartition(int N, int arr[])
{
int sum = 0;
for (int i=0; i<N; i++)
sum += arr[i];
if (sum % 2 != 0)
return 0;
sum = sum/2;
int row = N+1;
int col = sum+1;
int dp[2][col]; // change 1
for (int i=0; i<col; i++)
dp[0][i] = 0;
// for (int i=1; i<row; i++)
// dp[i][0] = 1;
dp[0][0] = 1; // change 2, due to space compression don't need above
int curr = 1; // change 3
for (int i=1; i<row; i++, curr^=1) { // change 4
for (int j=1; j<col; j++) {
dp[curr][j] = dp[curr^1][j]; // change 5
if(j-arr[curr^1] >= 0) // change 6
dp[curr][j] =max(dp[curr][j], dp[curr^1][j-arr[i-1]]); // change 7
}
}
return dp[curr^1][col-1]; // change 8
}
};
I'm trying to arrange my array in an asscending order but its giving me a different value:
#include <iostream>
int main ()
{
const int size = 5;
// 0 1 2 3 4
int arr[size] = {50,20,54,12,23};
for (int i=0; i<5; i++) //! bubble sort ascending order
{
for (int j=i; j<5; j++)
{ // 50 20
if (arr[j] > arr[j+1])
{
int temp = arr [j+1];
arr [j+1] = arr [j];
arr [j] = temp;
}
}
}
for (int i=0; i<5; i++)
{
std::cout<<arr[i]<<" ";
}
return 0;
}
The fact that it is not working, could it be of the empty array value (arr[6]) at the end of the loop that is messing up with the overall value? If so, it should be able to sort up till the last array size but its giving a different output instead
Output: 20 12 0 23 50
To prevent out of bound problems, change:
i<5 to size-1
j<5 to size-1-i
j=i to j=0
Code:
int main ()
{
const int size = 5;
// 0 1 2 3 4
int arr[size] = {50,20,54,12,23};
for (int i=0; i<size-1; i++) //! bubble sort ascending order
{
for (int j=0; j<size-1-i; j++)
{ // 50 20
if (arr[j] > arr[j+1])
{
int temp = arr [j+1];
arr [j+1] = arr [j];
arr [j] = temp;
}
}
}
for (int i=0; i<5; i++)
{
std::cout<<arr[i]<<" ";
}
return 0;
}
I need a function that can take to according to the x-axis of symmetry of the matrix.
input (matrix[i][j]):
1 2 3
4 5 6
7 8 9
output (matrix[i][j]):
7 8 9
4 5 6
1 2 3
How can i do this on the same matrix?
How should I write the inverse function?
void inverse(.......)
{
..
..
..
}
int main(){
int **matrix, i, j, k, row, column;
cout << "Row and column:" ;
cin >> row >> column;
matrix = new int*[row];
for (i=0; i<row; ++i){
matrix[i] = new int[column];
}
cout << "input elements of matrix: " << endl;
for(i=0; i<row; i++){
for (j=0; j<column; j++){
cin >> *(*(matrix+i)+j);
}
}
inverse (........);
for(i=0; i<row; i++){
for (j=0; j<column; j++){
cout << *(*(matrix+i)+j);
}
cout << endl;
}
return 0;
}
In this particular case, you can modify the loop to print the matrix backwards:
for(i = 0; i < row; i++) {
->
for(i = row - 1; i >= 0; i--) {
But if you want to actually do something to the data, my suggestion would be to refactor this code to use std::vector.
std::vector<std::vector<int> > matrix(numberOfRows, std::vector<int>(numberOfColumns));
// You can use std::vector<std::valarray<int> > matrix; alternatively.
You would then flip it simply by using an STL function:
std::reverse(matrix.begin(), matrix.end());
Edit:
Well, if you don't want to use std::vector for the time being and for this particular case, what you would do is this:
void flipMatrix(int** matrix, int rows, int columns) {
int middle = rows/2; // I expect it to truncate for an odd number of rows.
// Temporary row for swapping
int* tempRow;
for (int i = 0; i < middle; i++) {
// swap rows
tempRow = matrix[i];
matrix[i] = matrix[rows - i - 1];
matrix[rows - i - 1] = tempRow;
}
}
That is my function:
int main() {
double data[100];
int num;
cout<<"num= ";
cin>>num;
for(int i = 1; i <= num; i++) {
cout<<i<<" element = ";
cin>>data[i];
}
Sort(data, num);
for (int i = 1; i <= num; i++) {
cout<<data[i]<<endl;
}
return 0;
}
void Sort(double data[], int n) {
int i,j,k;
double min;
for(i = 0; i < n-1; i++) {
k = i;
min = data[k];
for(j = i+1; j < n; j++)
if(data[j] < min) {
k = j;
min = data[k];
}
data[k] = data[i];
data[i] = min;
}
}
if I write for exp. three elements: 8,9,1 again cout 8,9,1?
for(int i = 1; i <= num; i++) { // WRONG
I think you mean:
for(int i = 0; i < num; i++) { // RIGHT
Arrays in C are 0-indexed remember.
Your sorting function is fine. The only problem is that you enter elements at positions 1 through n, inclusive, while you should use 0 through n-1, inclusive, in both loops of the main() function.
If you need to print numbers 1 through n, use
cout<<(i+1)<<" element = ";
You should get used of the 0 index begin in the for loop
for(int i = 0; i < N; ++i)
so fixing these two index errors will make your code run properly.
the reason is:
if you write data to data[] using 1 as the begining, your data array's first item will be a random number:
if you insert 3 elements, the array will be like this:
data[0] = ??? // maybe a very very big number
data[1] = 8
data[2] = 9
data[3] = 1
and in your Sort function, your index begins at 0 and ends before num, that means your code would only sort data[0], data[1], data[2].
if you use: num = 3, 3 2 1 as your input data for the origin code you could see that 3 and 2 is sorted
I guess your Sort code is googled from somewhere, please try to understand it.
Good online algorithm course: https://www.coursera.org/course/algs4partI
a very good algorithm online book: http://algs4.cs.princeton.edu/home/
btw, for(j = i+1; j < n; j++) in the Sort function would be better if it has { } braces.