c++ variable sized arrays from Hackerrank with vectors - c++

I wanted to solve a challenge named "Variable sized Arrays" on Hackerrank and I wanted to do that using vectors. The Code I wrote, doesn't work properly and I tried debugging it, but I'm getting nowhere. I'll be grateful for
Here's the challenge:
Consider an n-element array,a, where each index i in the array contains a reference Kito an array of integers (where the value of Ki varies from array to array). See the Explanation section below for a diagram.
Given a, you must answer q queries. Each query is in the format i j, where i denotes an index in array and j denotes an index in the array located at a[i] . For each query, find and print the value of element j in the array at location on a[i]a new line.
Input Format
The first line contains two space-separated integers denoting the respective values of n (the number of variable-length arrays) and q (the number of queries).
Each line of the subsequent lines contains a space-separated sequence in the format k a[i]0 a[i]1 … a[i]k-1 describing the k-element array located at a[i].
Each of the q subsequent lines contains two space-separated integers describing the respective values of i (an index in array a) and j (an index in the array referenced by a[i]) for a query.
Sample Input
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
Sample Output
5
9
So here's my code for this (I'll leave it with the couts for debugging):
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
using std::endl;
int main() {
int numberOfQueries = 0;
int numberOfArrays = 0;
cout << "Enter Nr.Of Arrays followed by Nr.Of Queries:";
cin >> numberOfArrays >> numberOfQueries;
cout << "Nr.Of Arrays: " << numberOfArrays << endl;
cout << "Nr.Of Queries: " << numberOfQueries << endl;
vector<vector<int>>multiArray;
cout << "MultiArray size: " << multiArray.size();
while (numberOfArrays != 0) {
int vsize = 0;
cout << "\nenter array starting by its size: ";
cin >> vsize;
cout << " Size entered is: " << vsize << endl;
vector<int> vec1(vsize);
cout << "Array Size is: " << vec1.size() << endl;
//int element = 0;
while (cin >> vsize) {
cout << "Element is: " << vsize << "\n";
vec1.push_back(vsize);
};
multiArray.push_back(vec1);
numberOfArrays--;
cout << "MultiArray size: " << multiArray.size();
cout << "Nr.Of Arrays: " << numberOfArrays << endl;
};
while (numberOfQueries > 0) {
int i = 0, j = 0;
cout << "\nQuery indexes:";
cin >> i >> j;
cout << multiArray[i][j];
numberOfQueries--;
}
}

while (cin >> vsize) {
cout << "Element is: " << vsize << "\n";
vec1.push_back(vsize);
};
should be something like
for (int i = 0; i < vsize; ++i) {
int elem;
cin >> elem;
cout << "Element is: " << elem << "\n";
vec1.push_back(elem);
}
while (cin >> vsize) isn't going to stop asking for input until you get end of file or an error. But you know how many inputs to expect so code that in a for loop.

My answer.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,q;
cin >> n >> q ;
vector<int> a[n];
int k;
for(int i = 0; i < n; i++)
{
cin >> k;
for (int j = 0; j < k; j++)
{
int val_a_i_j;
cin >> val_a_i_j;
a[i].push_back(val_a_i_j);
}
};
for (int i = 0; i < q; i++)
{
int a_i, j;
cin >> a_i >> j;
cout << a[a_i][j] << '\n';
}
return 0;
}

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a , b;
cin >> a >> b;
vector<int> arr[a];
for(int i= 0 ; i < a ; i++)
{
int m;
cin >> m;
int o;
for(int j=0;j<m;j++)
{
cin >> o;
arr[i].push_back(o);
}
}
int r,s;
for(int k=1;k<b;k++)
{
cin>>r>>s;
cout <<a[r][s]<< endl;
}
return 0;
}

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n, q;
cin >> n >> q;
vector<int>* a;
a= new vector<int>[n];
int p;
int k;
for (p = 0;p < n;p++) {
cin >> k;
for (int i = 0; i < k; i++) {
int o;
cin >>o;
a[p].push_back(o);
}
}
int r, s;
for (p = 0;p < q;p++)
{
cin >> r >> s;
cout << a[r][s]<<endl;
}
return 0;
}

This problem is about handling vectors of the vector.
int main() {
int n,q;
cin>>n>>q;
vector<vector<int> > a;//creating vectors of vector
int k;
for (int i = 0; i < n; i++)
{
cin >>k;
vector <int> row; // creating vector
for (int j = 0; j < k; j++)
{
int val;
cin>> val;
row.push_back(val);
}
a.push_back(row);
}
for (int l=0; l < q; l++)
{
int i,j;
cin>>i>>j;
// checking boundary conditions
if ((i >= 0 && i < a.size() ) && (j >=0 && j < a[i].size()))
{
cout<<a[i][j]<<endl;
}
}
return 0;
}

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
vector<vector<int>> MultiArry;
vector<int> output;
int n1,n2, q;
int i,j;
cin >> n1 >> q;
MultiArry.resize(n1);
output.resize(q);
for(int i=0;i<n1;i++)
{
cin >> n2;
MultiArry[i].resize(n2);
for(int j=0;j<n2;j++)
{
cin >> MultiArry[i][j];
}
}
for(int ii=0;ii<q;ii++)
{
cin >> i >> j;
output[ii] = MultiArry[i][j];
}
for(int i=0;i<q;i++)
cout << output[i] << endl;
return 0;
}

Related

The following code of mine shows segmentation fault . How to prevent it?

The code below enters the number of arrays and the number of queries based on the arrays. The query consists of the array number and the desired element from that particular array.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct array
{
int arr[100000];
int n;
};
int main()
{
int i, j, b, d, e, f;
struct array a[100000];
cout << "Enter the number of arrays and the number of queries:";
cin >> b;
cin >> e;
cout << "Enter the value array size and enter the array elements:";
for(j = 0; j < b; j++)
{
cin >> a[j].n;
int c = a[j].n;
for(i = 0; i < c; i++)
{
cin>>a[j].arr[i];
}
}
for(i=0;i<e;i++)
{
cout << "Enter the query that consists of array number and the index of the desired element:";
cin >> d;
cin >> f;
cout << a[d].arr[f] << "\n";
}
return 0;
}

after inputting the values how can i display the values under one bracket e.g "{6,7,8,9}

#include <iostream>
using namespace std;
int main(){
int n;
cout << "No. of values : ";
cin >> n;
int array[n];
for (int i=0; i<n; i++)
{
cin >> array[i];
}
return 0;
}
You can use std::cout like :
#include <iostream>
using namespace std;
int main(){
int n;
cout << "No. of values : ";
cin >> n;
int array[n];
for (int i=0; i<n; i++)
{
cin >> array[i];
if(i ==0)
std::cout<<"{" <<array[i];
else if(i == n-1)
std::cout<<","<<array[i]<<"}";
else
std::cout<<","<<array[i];
}
return 0;
}
#mystic's answer uses arrays, which works fine. You can also use vector. There are more advanced methods of iterating over a vector, but I have not included that here to keep it simple.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> intVector{};
int n;
int input;
cout << "No. of values : ";
cin >> n;
for (int i = 0; i < n; i++) {
cin >> input;
intVector.push_back(input);
}
// Print out the array
cout << "{";
for(int i = 0; i < intVector.size(); i++) {
cout << intVector[i];
// print out the comma, except for the last number
if(i < intVector.size() - 1) {
cout << ", ";
}
}
cout << "}" << endl;
return 0;
}
If you want to use an iterator for printing the array, you can replace the print loop with this code:
// Print out the array
cout << "{";
for(auto i=intVector.begin(); i!=intVector.end(); ++i) {
if (i != intVector.begin()) {
cout << ", ";
}
cout << *i;
}
cout << "}" << endl;

Simple Array Sum in c++

I'm beginner in C++, and I've got a question about a simple sum code in c++.
Here is my code :
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n;
int sum;
int arr_i = 0;
cin >> n;
vector<int> arr(n);
while (arr_i != n)
{
cin >> arr[arr_i];
sum += arr[arr_i];
//cout << sum << endl;
if (arr_i == n - 1)
cout << sum;
arr_i++;
}
return 0;
}
The output doesn't print the correct answer without "cout << sum" before the if condition.
How can I solve this problem ?
You forget to initialize sum to 0.
int sum = 0;
As the previous post mentioned, sum was not initialized to 0. In terms of good practices and styles its a good idea to initialize any variables that are modified within a loop right before the loop body so that someone reading the code can easily grasp the context of your variables.
int main()
{
int n;
int sum;
int arr_i;
cin >> n;
vector<int> arr(n);
sum = 0;
arr_i = 0;
while (arr_i != n)
{
cin >> arr[arr_i];
sum += arr[arr_i];
//cout << sum << endl;
if (arr_i == n - 1)
cout << sum;
arr_i++;
}
return 0;
}
or as I prefer a "for" loop...
int main()
{
int n;
int sum;
int arr_i;
cin >> n;
vector<int> arr(n);
for (sum = 0, arr_i = 0; arr_i != n; arr_i++)
{
cin >> arr[arr_i];
sum += arr[arr_i];
//cout << sum << endl;
if (arr_i == n - 1)
cout << sum;
}
return 0;
}

how to print an array backwards

The user enteres a number which is put in an array and then the array needs to be orinted backwadrds
int main()
{
int numbers[5];
int x;
for (int i = 0; i<5; i++)
{
cout << "Enter a number: ";
cin >> x;
numbers[x];
}
for (int i = 5; i>0 ; i--)
{
cout << numbers[i];
}
return 0;
}
You're very close. Hope this helps.
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int numbers[5];
/* Get size of array */
int size = sizeof(numbers)/sizeof(int);
int val;
for(int i = 0; i < size; i++) {
cout << "Enter a number: ";
cin >> val;
numbers[i] = val;
}
/* Start index at spot 4 and decrement until k hits 0 */
for(int k = size-1; k >= 0; k--) {
cout << numbers[k] << " ";
}
cout << endl;
return 0;
}
You are very close to your result but you did little mistakes, the following code is the correct solution of the code you have written.
int main()
{
int numbers[5];
int x;
for (int i = 0; i<5; i++)
{
cout << "Enter a number: ";
cin >> numbers[i];
}
for (int i = 4; i>=0; i--)
{
cout << numbers[i];
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
//get size of the array
int arr[1000], n;
cin >> n;
//receive the elements of the array
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
//swap the elements of indexes
//the condition is just at "i*2" be cause if we exceed these value we will start to return the elements to its original places
for (int i = 0; i*2< n; i++)
{
//variable x as a holder for the value of the index
int x = arr[i];
//index arr[n-1-i]: "-1" as the first index start with 0,"-i" to adjust the suitable index which have the value to be swaped
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = x;
}
//loop for printing the new elements
for(int i=0;i<n;i++)
{
cout<<arr[i];
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
//print numbers in an array in reverse order
int myarray[1000];
cout << "enter size: " << endl;
int size;
cin >> size;
cout << "Enter numbers: " << endl;
for (int i = 0; i<size; i++)
{
cin >> myarray[i];
}
for (int i = size - 1; i >=0; i--)
{
cout << myarray[i];
}
return 0;
}
of course you can just delete the cout statements and modify to your liking
this one is more simple
#include<iostream>
using namespace std;
int main ()
{
int a[10], x, i;
cout << "enter the size of array" << endl;
cin >> x;
cout << "enter the element of array" << endl;
for (i = 0; i < x; i++)
{
cin >> a[i];
}
cout << "reverse of array" << endl;
for (i = x - 1; i >= 0; i--)
cout << a[i] << endl;
}
answer in c++. using only one array.
#include<iostream>
using namespace std ;
int main()
{
int array[1000] , count ;
cin >> count ;
for(int i = 0 ; i<count ; i++)
{
cin >> array[i] ;
}
for(int j = count-1 ; j>=0 ; j--)
{
cout << array[j] << endl;
}
return 0 ;
}
#include <iostream>
using namespace std;
int main ()
{
int array[10000];
int N;
cout<< " Enter total numbers ";
cin>>N;
cout << "Enter numbers:"<<endl;
for (int i = 0; i <N; ++i)
{
cin>>array[i];
}
for ( i = N-1; i>=0;i--)
{
cout<<array[i]<<endl;
}
return 0;
}

how to save the sorted arrays in textfile?

I have a program that sorted arrays how can i save in text file?
for example: the sorted arrays is: 1, 2, 3, 4, 5.
how can i save in text file named. Sorted elements".
I've tried many ways but the sorted array wouldn't save in text file.
I am a newbie so I find it difficult.
here is my code.
#include <iostream>
using namespace std;
int main() {
cout << "Enter number of element:";
int n; cin >> n;
int a[n];
for(int i=0;i<n;i++)
{
cout << "element number " << (i+1) << " : ";
cin >> a[i];
}
int e=1, d=3;
int i, j, k, m, digit, row, col;
int length = sizeof(a)/sizeof(int);
int bmat[length][10];
int c[10];
for(m=1;m<=d;m++)
{
for(i=0;i<10;i++)
{
c[i]=-1;
}
for(i=0;i<length;i++)
{
digit=(a[i]/e)%10;
c[digit]++;
row=c[digit];
col=digit;
bmat[row][col]=a[i];
}
k=-1;
for(i=0;i<10;i++)
{
if(c[i]!=-1)
{
for(j=0;j<=c[i];j++)
{
k++;
a[k]=bmat[j][i];
}
}
}
e=e*10;
}
cout << endl;
cout << "Sorted array:" << endl;
for(int i=0;i<n;i++)
{
cout << a[i] << " , ";
}
cout << endl;
system("pause");
return 0;
}
//Use this code
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
using namespace std;
int main()
{
int n = 0;
cout << "Enter number of element:";
cin >> n;
//Data Structure
std::vector<int> list;
//push back element in vector
for(register int i=0;i<n;++i)
list.push_back(rand()%10 + 1);
//do shuffling before sorting because rand() generates increasing order number
std::random_shuffle(list.begin(),list.end());
std::sort(list.begin(),list.end());
ofstream textfile;
textfile.open ("E:\\example.txt");
for(size_t i= 0;i<list.size();++i)
textfile << list[i] <<" ";
textfile.close();
}
If you can write the sorted array to std::cout, then you can write it to a file. In C++, the console is the same as a file.
Put this at the end of main:
cout << "Sorted array:" << endl;
print_array( std::cout, a, n ); // Show the results to the user.
std::ofstream save( "array.txt" ); // Open a new file (or overwrite).
print_array( save, a, n ); // Save the results for later.
system("pause");
return 0;
}
and put the printing code in a new function, which may be defined before main:
void print_array( std::ostream & s, int * a, int n ) {
for(int i=0;i<n;i++)
{
s << a[i] << " , ";
}
s << endl;
}
#include<iostream>
#include<fstream>
using namespace std;
int compare(int, int);
void sort(int[], const int);
int compare(int x, int y){
return(x > y);
}
void swap(int *x, int *y){
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void display(int array[], int n){
for (int i = 0; i<n; i++) {
cout << array[i] << " ";
}
cout << endl;
}
void writeToFile(int array[], int n){
ofstream myfile;
myfile.open("example.txt");
for (int i = 0; i<n; i++) {
myfile << array[i];
if (i != n - 1){
myfile << ", ";
}
}
myfile.close();
}
void sort(int table[], const int n) {
for (int i = 0; i < n; i++){
for (int j = 0; j < n - 1; j++) {
if (compare(table[j], table[j + 1]))
swap(&table[j], &table[j + 1]);
}
}
}
int main(){
int quantity;
int* tab;
ofstream outfile;
cout << "Enter number of element: ";
cin >> quantity;
tab = new int[quantity];
cout << "Element:\n\n" << endl;
for (int i = 0; i < quantity; i++){
int x = i;
cout << "#" << ++x << ":";
cin >> tab[i];
}
sort(tab, quantity);
cout << "The Sorted Elements are: ";
display(tab, quantity);
writeToFile(tab, quantity);
cout << endl;
getchar();
getchar();
//system("pause");
return 0;
}
in short, add this block to your code:
ofstream myfile;
myfile.open("example.txt");
for (int i = 0; i<n; i++) {
myfile << array[i];
if (i != n - 1){
myfile << ", ";
}
}
myfile.close();
You can use C++ fstream class, since you want to output, you can use ofstream here. You should just replace some "cout" with ofstream instance:
At the beginning of the code state it:
ofstream ofs("./sorted_elem.txt", ofstream::out);
When want to output:
ofs << "Sorted array:" << endl;
for(int i=0;i<n;i++)
{
ofs << a[i] << " , ";
}
ofs << endl;
In C++ you really want to use std::vector or some other nice container for storing arrays of numbers. For writing an array to file you need to open the file and individually write each element to the file (all untested).
#include <fstream>
int main()
{
std::ofstream fp("output.txt");
int data[5]; // todo: fill
for (unsitned i = 0; i < 5; ++i)
{
fp << data[i] << ' ';
}
}
And to read again:
#include <fstream>
int main()
{
std::ifstream fp("output.txt");
// todo: Determine the size of the array or guess it (don't guess it!)
unsigned array_size = 5;
int data[array_size];
int n = 0;
while (fp.good() && n < array_size) fp >> data[n++];
}
But because we are using C++, we can use std::vector:
#include <fstream>
#include <vector>
int main()
{
std::vector<int> me(5); // todo: fill
std::ofstream fp("output.txt");
for (size_t i = 0; i < me.size(); ++i) fp << me[i] << ' ';
// C++11: for (int d : me) fp << d << ' ';
}
And,
#include <fstream>
#include <vector>
int main()
{
std::ifstream fp("output.txt");
std::vector<int> data;
double buf;
while (fp >> buf) data.push_back(buf); // no longer need to guess
}
I think, the copy option was not demonstrated here so far.
Please check this code. (Assuming your vector is ready to use, I've skipped it).
The example uses a C-array and a vector. Please use the later in your code whenever possible. But however, for copy-function both work:
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <fstream>
int main () {
int a[10]={0,1,2,3,4,5,6,7,8,9};
std::vector<int> v; for (int i=0; i<10; ++i)v.push_back(i*10); //0, 10, 20,...
std::ofstream fs_a( "c:/temp/out_a.txt" );
//store space separated
std::copy ( a, a+sizeof(a)/sizeof(a[0]), std::ostream_iterator<int>( fs_a, " ") );
//store coma-separated, as one-liner
std::copy ( v.begin(), v.end() ), std::ostream_iterator<int>( std::ofstream( "c:/temp/out_v.txt" ), ",") );
return 0;
}