Wrong output by for loop - list

I am using a variable j which am incrementing everytime a for loop executes to count the no of loops it ran and adding the value of i in list a and then adding the list a to b but on printing b it is printing wrong output.
My Code:-
void main() {
var a=[];
var b=[];
int j=0;
for (int i = 0; i < 5; i++) {
j++;
a.add(i);
if(j>=4)
{
b.addAll(a);
print(b);
}
}
}
Logically it should print [0,1,2,3,4] but it is printing:-
[0, 1, 2, 3]
[0, 1, 2, 3, 0, 1, 2, 3, 4]

The reason that it is printing it twice and the second time with the same list duplicated is because of your logic of j>=4. It is getting hit twice. If you only want it to get it once then you'll need to remove the =
void main() {
var a=[];
var b=[];
int j=0;
for (int i = 0; i < 5; i++) {
j++;
a.add(i);
if(j>4)
{
b.addAll(a);
print(b);
}
}
}
this happens because you are referencing j instead of i. j will hit 5, therefore your logic j>=4 applies to 4 and 5, whereas i will not because it will only get up to 4.

Related

Best way to remove non uniques values from an array, keep the order, and not use vectors?

I apologize if this has been asked, but I ran into a coding question, which was supposed to be simple but I struggled on. Please provide a link if already answered (I may just be bad at searching).
Question: Given the sample code fill in the function to return only unique values in the array. Values must keep order.
Example Input : 1, 2, 3, 10, 4, 3, 2, 10, 1, 11, 6
Example Output: 1 2 3 10 4 11 6
Below is my solution, but I can not seem to think of an easy solution that does not include the use of a vector to store unique values. The tester did not like the use of a vector so I can only assume additional headers / libraries were unacceptable. Any other solutions? I am guessing the tester was looking for the array to be filtered in place.
#include <iostream>
#include <vector> //I was not allowed to add this...
//Function to fill in...
int fxn(int *a, int size)
{
std::vector<int> temp;
for(int i(0); i < size; ++i)
{
bool found(false);
for(auto j : temp)
{
if( j == a[i])
{
found = true;
break;
}
}
if(!found)
{
temp.push_back(a[i]);
}
}
int *ptr_a = &a[0];
for(auto j : temp)
{
*ptr_a = j;
++ptr_a;
}
return size - temp.size();
}
//The rest untochable...
void print(int *a, int size)
{
for(int i(0); i < size; ++i)
{
std::cout << a[i] << " ";
}
std::cout << std::endl;
}
int main(void)
{
int a[] = { 1, 2, 3, 10, 4, 3, 2, 10, 1, 11, 6 };
int size = 11;
int count = fxn(a, size);
print(a, size - count);
return 0;
}
Admittedly, this problem would be easier if you could use external libraries, but if you are certain you cannot, it is still solvable.
I read the question incorrectly the first time. Here is a link to as similar question.
#include<iostream>
using namespace std;
int removeDuplicates(int arr[], int n)
{
int j = 0;
for (int i=0; i < n; i++){
for(int j=0;j<i;j++){
if(arr[i]==arr[j]){
n--;
for (int k=i; k<n; k++){
arr[k]=arr[k+1];
}
i--; // you forgot to decrement i
}
}
}
return n;
}

Vector subscript out of range error, C++, bubble sort

I need to do a simple bubble sort in C++ and i want to learn how to use std::vector. But when i run this programm i got this error...
I don't understand why... because i don't think my iteration go out of the range.
Any idea ?
#include <iostream>
#include <vector>
using namespace std;
void triABulle(vector<int>&, int, int);
void echanger(vector<int>&, int, int);
void affiche(vector<int>&);
int main() {
vector<int> tab = { 3, 4, 56, 3, 2, 5, 64, 3453, 34 };
affiche(tab);
triABulle(tab, 0, tab.size());
cin.get();
return 0;
}
void triABulle(vector<int>& tab, int begin, int end) {
for (size_t i = 1; i <= end-begin; i++)
{
for (size_t j = end; j >= begin+i; j--)
{
if (tab[j] < tab[j-1])
{
echanger(tab, j, j-1);
cout << "SWAP!" << endl;
affiche(tab);
}
}
}
}
void echanger(vector<int>& tab, int i, int j) {
int tmp = tab[i];
tab[i] = tab[j];
tab[j] = tmp;
}
void affiche(vector<int>& tab) {
for (size_t i = 0; i < tab.size() ; i++)
{
cout << tab[i] << ' ';
}
cout << endl;
}
Note that C++ is 0-indexed, meaning indicies start at 0. This implies that if we declare
vector<int> tab = { 3, 4, 56, 3, 2, 5, 64, 3453, 34 };
then the access
tab[tab.size()]
will be out of bounds. Observe that you also call
triABulle(tab, 0, tab.size()); // so tab.size() == end
and have an inner loop of
for (size_t j = end; j >= begin+i; j--) {
if (tab[j] < tab[j-1]) // results in going out of bounds
{
...
}
}
your if statement will be out of bounds since end == tab.size(). This access is why you get the subscript out of range error.
In C++ array indexes go from 0 to length-1, not 1 to length.
The technique of half open intervals is useful.
for (int i = 0; i < end-begin; i++)
{
for (int j = end-1; j >= begin+i; j--)

How to double values in 2d array? C++

I'm trying to double each number in 2D arrays. For example the values in array1 would become {2,4,6}{4,8,12}{6,12,18}. The problem is that my code doubles the only the first number. Can someone give me some direction on what to do?
#include <iostream>
#include <iomanip>
using namespace std;
const int N = 3;
int doubleValues(int arr[][N])
{
for (int i = 0; i < N; i++)
{
arr[i][N] *= 2;
for (int j = 0; j < N; j++)
{
arr[N][j] *= 2;
return arr[i][j];
}
}
}
void showArray(int arr[][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
cout << setw(4) << arr[i][j] << " ";
}
cout << endl;
}
}
int main()
{
int array1 [N][N] = {
{ 1, 2, 3 } ,
{ 2, 4, 6 } ,
{ 3, 6, 9 }
};
int array2 [N][N] = {
{ 3, 4, 5 } ,
{ 6, 8, 10 } ,
{ 9, 12, 15 }
};
cout << "The values for array1 doubled are: \n";
doubleValues(array1);
showArray(array1);
cout << "The values for array2 double are: \n";
doubleValues(array2);
showArray(array2);
system("pause");
}
You have a return arr[i][j] in the inner loop of your doubleValues function. After doubling the first element, your function returns without doing any more work.
The solution is to remove this return statement. (And change doubleValues to a void function, because it doesn't need to return a value.)
Also, your doubleValues function seems to be modifying the wrong elements anyway. Both your accesses to arr[i][N] and arr[N][j] access elements out of bounds of your declared array size. You should probably be modifying arr[i][j] within your loop.
If you can use std::array for this project (since you know the size of your array at compile time) , you can use the functions within the <algorithm> header to easily implement your doubleValues function and not worry about hand-writing the loops.
template<typename T, std::size_t size>
void doubleValues(std::array<T,size>& arr)
{
std::transform(std::begin(arr),std::end(arr),std::begin(arr), [](auto x) { return 2 * x; });
}
This method would require that you break your 2d-array structure down into a single dimension, which can be accomplished with relative ease. For example,
std::array<int,N*N> array1 = { 1, 2, 3, 2, 4, 6, 3, 6, 9 };
std::array<int,N*N> array2 = { 3, 4, 5, 6, 8, 10, 9, 12, 15}
In the case where the size of the arrays could change dynamically, you can swap out std::array for std::vector.

Sorting 2D Array C++

Is it possible to sort a 2D Array using qsort or std::sort in C++ such that the elements are in increasing order when read from left to right in each row or from top to bottom in each column?
For example,
13, 14, 15, 16
1, 4, 3, 2
7, 5, 7, 6
9, 10, 11, 12
Becomes:
{ 1, 2, 3, 4 }
{ 5, 6, 7, 8 }
{ 9, 10, 11, 12 }
{ 13, 14, 15, 16 }
I know you can do it by creating two comparison functions and then first sorting each row then comparing the first elements of each row to establish the columns, but is there a way to do it in one function itself?
# include <iostream>
using namespace std ;
void swap (int &x , int &y)
{
int temp = x ;
x = y ;
y = temp ;
}
void main ()
{
int arr [3][3] = {{90,80,70},{60,50,40},{30,100,10}} ;
int x ;
for (int k = 0; k < 3; k++)
{
for (int m = 0; m < 3; m++)
{
x = m+1;
for (int i = k; i < 3 ; i++)
{
for (int j = x; j < 3; j++)
{
if (arr [k][m] > arr [i][j])
swap(arr [k][m] ,arr [i][j]);
}
x=0;
}
}
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr [i][j] << " ";
}
}
system("pause");
}
C++ Sorting 2-D array ascendingly
Yes. C++ STL library is built with separation of algorithms and containers. What links them together is iterators. Raw pointer is iterator, therefore it is possible to initialize vector with raw pointers and then sort that vector as usual.
std::vector<int> v(arr2d, arr2d + N); // create a vector based on pointers
// This assumes array is contiguous range
// in memory, N=number of elemnts in arr2d
// using default comparison (operator <):
std::sort (v.begin(), v.end());
// cout by 4 elements in a row
In theory you should be able to input the 16 numbers into an array. Use a for loop, maybe even a nested one, to sort the numbers. Then as for output you want the ascending numbers in four groups of four?
cout<<Vector[0]<<Vector[1]<<Vector[2]<<Vector[3]<<endl;
cout<<Vector[4]<<Vector[5]<<Vector[6]<<Vector[7]<<endl;
cout<<Vector[8]<<Vector[9]<<Vector[10]<<Vector[11]<<endl;
cout<<Vector[12]<<Vector[13]<<Vector[14]<<Vector[15]<<endl;
very arbitrary but I'm not quite sure of the question.
First Make a 2D vector .
Sort each vector in this 2D vector
Sort the whole vector
Code :
#include <iostream>
#include <vector>
#include <algorithm>
template <class T>
void Sort2dArray(std::vector<std::vector<T>> & numbers)
{
for(auto & i : numbers){//sort each vector<T> in numbers
std::sort(i.begin(),i.end());
}
std::sort(numbers.begin(),numbers.end(),[](//sort numbers by defining custom compare
const std::vector<T>& a,const std::vector<T>&b){
for(int i=0;i<a.size()&&i<b.size();i++)
{
if(a[i]>b[i])
return false;
else if(a[i]<b[i])
return true;
}
return a.size()<b.size() ? true : false;
});
}
int main()
{
std::vector<std::vector<int>> numbers={ {13, 14, 15, 16},
{1, 4, 3, 2},
{8, 5, 7, 6},
{9, 10, 12,11}};
Sort2dArray(numbers);//sort array
//write sorted array
for(auto i:numbers)
{
for(auto j:i)
std::cout<<j<<" ";
std::cout<<"\n";
}
}
**Sorting 2D array in c++**
#include <iostream>
using namespace std;
int main()
{
int i,j,k,m,temp,n,limit;
int** p;
cout<<"Enter the limit:";
cin>>limit;
p=new int*[limit];
//inputing
for(i=0;i<limit;i++)
{
p[i] = new int[limit];
for(j=0;j<limit;j++)
{
cin>>p[i][j];
}
}
//sorting
for(i=0;i<limit;i++)
{
for(j=0;j<limit;j++)
{
if (j==limit-1 && i<limit-1)
{
n =-1;
m=i+1;
}
else
{
m=i;
n=j;
}
for(k=n+1;k<limit;k++)
{
if(p[i][j] > p[m][k] )
{
temp = p[i][j];
p[i][j] = p[m][k];
p[m][k] = temp;
}
if(k==limit-1 && m<limit-1) { m++; k=-1; }
}
}
}
//displaying
for(i=0;i<limit;i++)
{
for(j=0;j<limit;j++)
{
cout<<p[i][j]<<endl;
}
}
return 0;
}

Linear Search returning array with indices value is found at

I attempted a program to return an array with the indicies of the array where a specific inputed value is found, but every run results in an error, which seems to be an infinite run time. The error seems to be occuring right after printing out the last of the indicies found.
Can anyone help?
(Side note: I've seen multiple pages about deleting pointers when done with them; should I be doing that here?)
Forgot to mention - I want the first slot of the returned array to save the size of the array, so that it can be accessed easily later on in the program
#include <iostream>
#include <vector>
using namespace std;
int* linearSearch(int* n, int k, int f) {
// Input: Index 0 Address ; Size of Array; Element to Search
// Output: Array of Found Indicies
vector <int> a;
int* b;
for(int i = 0; i < k; i++)
if(n[i] == f)
a.push_back(i);
*b = a.size();
for(int i = 0; i < a.size(); i++)
b[i + 1] = a[i];
return b;
}
int main() {
int c[10] = {4, 4, 6, 3, 7, 7, 3, 6, 2, 0};
int* k = linearSearch(&c[0], sizeof(c)/sizeof(int), 4);
for(int i = 0; i < k[0]; i++) {
cout << "Found at index: " << k[i + 1] << endl;
}
return 0;
}
int* b;
....
*b = a.size();
b has to be allocated. Try following:
int* b = new int[a.size() + 1];
b[0] = a.size();
I see what you meant. b will have magically length in first element. This was in Pascal/Delphi but not the case in C/C++.
You are writing to heap memory that you never claimed.
int* b;
This pointer, having never been initialized, points to an undefined memory address. Then when you use the indexing operator to assign your matches, you are writing to the subsequent bytes following the undefined memory address.
You need to allocate space for storing the results using the 'new[]' operator. Additionally, if you had correctly claimed the memory, you would be assigning the number of match results to the first element in the result array - something that doesn't seem to be your intention.
Take a look at dynamic memory allocation in C++ using the new [] operator.
If you use std::vector anyway, why not to use it where it is needed the most? Also if you not suppose to modify array by that pointer express that by const pointer:
std::vector<int> linearSearch(const int* n, int k, int f)
{
std::vector<int> res;
for(int i = 0; i < k; i++)
if(n[i] == f) res.push_back(i);
return res;
}
int main() {
int c[10] = {4, 4, 6, 3, 7, 7, 3, 6, 2, 0};
std::vector<int> k = linearSearch(&c[0], sizeof(c)/sizeof(int), 4);
for(int i = 0; i < k.size(); i++) {
cout << "Found at index: " << k[i] << endl;
}
return 0;
}
This is not perfect but this is much closer to a correct implementation and you should be able to take it further with some work:
#include <iostream>
#include <vector>
using namespace std;
std::vector<int> linearSearch(int* n, int k, int f)
{
vector <int> a;
for(int i = 0; i < k; i++)
{
if(n[i] == f)
{
a.push_back(i);
}
}
return a ;
}
int main() {
int c[10] = {4, 4, 6, 3, 7, 7, 3, 6, 2, 0};
std::vector<int> result = linearSearch(&c[0], sizeof(c)/sizeof(int), 4);
for(unsigned int i = 0; i < result.size(); i++)
{
cout << "Found at index: " << result[i + 1] << endl;
}
return 0;
}