C++ Array swapping and find smallest element - c++

I am trying to find first smallest array but my code does not display any output. There are no errors or warnings. Actually, I am trying to check an algorithm that I got as an assignment from my university.
#include <iostream>
using namespace std;
int main(){
int arr[7]= {8,4,6,9,2,3,1};
int n = sizeof(arr)/sizeof(arr[0]);
int smallest = 0;
for(int j = 1; j = (n-1); j = (j + 1) )
{
smallest= j ;
for(int i = (j+1); i = n ; i = (i + 1))
{
if (arr[i]<arr[smallest])
{
smallest = i;
int swaper = arr[j];
arr[j] = arr[smallest];
arr[smallest] = swaper;
}
}
}
for(int a = 1; a = n; a = (a + 1))
{
cout<<arr[a];
}
return 0;
}

There are three errors with this code:
for(int a = 1; a = n; a = (a + 1))
{
cout<<arr[a];
}
Firstly, arrays start from zero, not one. So the first part of the for statement should be int a = 0;.
Secondly, you are not comparing a and n, you are assigning n to a, (and the value is non-zero, so you always keep going). The equality test is ==, but you don't want that anyway!
Thirdly, the loop condition is for when to keep going, not when to stop. So you need either < or != (either will work, people have long arguments about which is preferable).
The normal way to write a loop over a range of integers in C++ is:
for (int a = 0; a < n; a++)
You are at least consistent, and have made the same mistake in every loop. You will need to fix it in every loop.

# include <iostream>
using namespace std;
int main ()
{
int a[100][100],n,k,i,j,aux,mi=0;
cin>>n>>k;
for(i=1;i<=n;i++)
for(j=1;j<=k;j++)
cin>>a[i][j];
for(i=1;i<=n-1;i++)
for(j=i+1;j<=n;j++)
if(a[i][k]>a[j][k])
{aux=a[i][k];
a[i][k]=a[j][k];
a[j][k]=aux;
} //until here you are sorting the 2D array
for(i=1;i<=n;i++) {
for(j=1;j<=k;j++) {
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
mi=a[1][1];
for (i=1; i<=n; i++)
{
for (j=1; j<=n; j++)
if (mi<a[i][j])
mi=a[i][j];
} //here you're finding the smallest element
cout<<mi;
return 0;
}
The Code doesn't compile, but the idea should solve 90%, you just have to write the code.

Related

Sorting integers in an array. But its not working for some cases

So I've written this to print "Yes when the code is in ascending order and "No" when it is not. But if I start with equal values in the beginning, the program prints an incorrect result. I don't understand why the if statement runs even if the condition isn't met.
#include <iostream>
using namespace std;
int main()
{
int N, i;
scanf("%d", &N);
int arr[N];
for(i = 1; i <= N; i++)
{
scanf("%d", &arr[i - 1]);
}
for(i = 1; i <= N; i++)
{
if(arr[i - 1] > arr[i])
{
printf("No");
return 0;
}
}
printf("Yes");
return 0;
}
You have an off by one error where you skip the first element of your array and go one past the last element. If your array has N elements, it goes from array[0] to array[N-1]. Change this here:
for(i = 1; i <= N; i++){
To this here:
for(i = 0; i < N; i++){
The second for(i = 1; i <= N; i++) where you do the check can start at 1 since you look at arr[i - 1] within, but it should be i < N instead of i <= N nevertheless.
Furthermore, int arr[N]; doesn't work in C++ (some compilers will tolerate it, but not all of them). Try std::vector<int> arr(N); instead.

Time Limit Exceeded on Hackerrank

I successfully solved a question on Hackerrank, and it passed all test cases but I got an error Time Limit Exceeded. I'm guessing if I optimize my code it would work,but I can't think of any way to make my code more efficient.
The question is:
A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].
Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers.
Can any one please guide me on how to make this code more efficient?
My code is:
vector<int> array_left_rotation(vector<int> a, int n, int k) {
for (int j = 0; j < k; j++){
a[n] = a[0];
for (int i = 0; i < n; i++){
a[i] = a[i+1];
}
a[n-1] = a[n];
}
return a;
}
n is the number of elements in the array
k is the number of rotations to be performed
You don't need to actually rotate the array for this problem. The formula (i + k) % n will give you the element at index i in an array that has been rotated k times to the left. Knowing this you can pass through the array once accessing each element in this manner:
int main() {
int* arr, n, k, i;
cin >> n >> k;
arr = new int[n];
for (i = 0; i < n; ++i)
cin >> arr[i];
for (i = 0; i < n; ++i)
cout << arr[(i + k) % n] << " ";
}
Instead of performing k rotations, try performing a k-rotation:
Rotate the entire array left by k in one go. That's much more efficient.
If another vector will not cause a space problem, you may just copy them with an offset:
//Not tested
vector<int> array_left_rotation(vector<int> a, int n, int k) {
std::vector<int> result(n);
for (int j = 0; j < k; j++){
result[j]=a[(j+k)%n];
}
return result;
}
using namespace std;
#include<iostream>
int main()
{
int a[1000000],b[1000000];
int n,d;
cin>>n;
cin>>d;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int i=0,j;i<n;i++)
{
if(i==0)
{
j=n-d;
b[j]=a[i];
}
else if(i==d)
{
j=i-d;
b[j]=a[i];
}
else
{
j=(n-d+i);
if(j>n)
{
j=(i-d);
b[j]=a[i];
}
else
{
j=(n-d+i);
b[j]=a[i];
}
}
}
for(int i=0;i<n;i++)
{
cout<<b[i]<<" ";
}
}
This passes all the test cases. What i actually did is to move each element in array a[i] k times in an another array b[i] as there is no space constraint.

How can I properly add and access items to a multidimensional vector using loops?

I have this program that is trying to determine how many unique items are within some intersecting sets. The amount of input entirely depends on the the first value n, and then the amount of sets entered afterward. For example, if I start with entering n = 2, I am expected to enter 2 integers. The program then determines how many intersections there are between n items (this is like choosing 2 items from n items). This goes on as k increments. But that's kind of beyond the point. Just some background info.
My program adapts correctly and accepts the proper amount of input, but it stops working properly before the first for loop that is outside of the while loop. What I have tried to do is make a vector of integer vectors and then add every other row (when index starts at 0 AND index starts at 1). But I am guessing I have constructed my vectors incorrectly. Does anybody see an error in my vector logic?
#include <iostream>
#include <vector>
using namespace std;
int fact (int m) {
if (m <= 1)
return 1;
return m * fact(m - 1);
}
int comb (int n, int k) {
return fact(n)/(fact(n-k)*fact(k));
}
int main() {
int n = 0;
int k = 2;
int sum = 0;
int diff = 0;
int final = 0;
vector <vector <int> > arr;
cin >> n;
while (n > 0) {
vector <int> row;
int u;
for (int i = 0; i < n ; ++i) {
cin >> u;
row.push_back(u);
}
arr.push_back(row);
n = comb(row.size(), k);
k++;
}
for (int i = 0; i < arr.size(); i+2)
for (int j = 0; j < arr[i].size(); ++j)
sum += arr[i][j];
for (int i = 1; i < arr.size(); i+2)
for (int j = 0; j < arr[i].size(); ++j)
diff += arr[i][j];
final = sum - diff;
cout << final;
return 0;
}
for (int i = 0; i < arr.size(); i+=2)
^
You want to do i+=2 or i=i+2, else the value of i is never changed, leading to an infinite loop.

Selection sort ascending

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.

Matrix Multiplication Using win32 threads

I have no idea what's wrong with my code ... It always return zeros in all the elements. A hint of where is the problem would be great :)
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
int nGlobalCount = 0;
int thread_index = 0;
int num_of_thr=5;
int a[4][4], b[4][4], c[4][4];
int i, j, k;
struct v {
int i; /*row*/
int j; /*column*/
};
DWORD ThreadProc (LPVOID lpdwThreadParam ) {
//
struct v *input = (struct v *)lpdwThreadParam;
int avg=4*4/num_of_thr;
int count=0;
for(int i = 0; i <= 3 ; i++) {
for(int j = 0; j <= 3; j++) {
int sum=0;
for ( k = 0 ; k <= 3; k++) {
sum=sum+((a[input->i][k])*(b[k][input->j]));
c[input->i][input->j]=sum;
count++;
}
}
}
//Print Thread Number
//printf ("Thread #: %d\n", *((int*)lpdwThreadParam));
//Reduce the count
return 0;
}
int main() {
// int x=0;
cout<<"enter no of threads : ";
cin>>num_of_thr;
DWORD ThreadIds[num_of_thr];
HANDLE ThreadHandles[num_of_thr];
//struct v {
// int i; /*row*/
// int j; /*column*/
//};
struct v data[num_of_thr];
int i , j , k;
for ( int i = 0 ; i <= 3; i++) {
for (int j = 0 ; j <= 3 ; j++) {
a[i][j] = rand() % 10;
b[i][j] = rand() % 10;
c[i][j] = 0;
}
}
for(int i = 0; i < num_of_thr/2; i++) {
for(int j = 0; j < num_of_thr/2; j++) {
data[thread_index].i = i;
data[thread_index].j = j;
ThreadHandles[thread_index] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadProc, &data[thread_index], 0,&ThreadIds[thread_index]);
thread_index++;
}
}
WaitForMultipleObjects(num_of_thr, ThreadHandles, TRUE, INFINITE);
cout<<"The resultant matrix is "<<endl;
for ( i = 0 ; i < 4; i++) {
for ( j = 0 ; j < 4 ; j++)
cout<<c[i][j]<<" ";
cout<<endl;
}
for (int i=0; i<num_of_thr; i++)
CloseHandle(ThreadHandles[i]);
return 0;
}
At a GLANCE, your sum declaration in the loop looks sketchy.
for(int i = 0; i <= 3 ; i++) {
for(int j = 0; j <= 3; j++) {
for ( k = 0 ; k <= 3; k++)
{
int sum=sum+((a[input->i][k])*(b[k][input->j])); // this declaration seems wrong
c[input->i][input->j]=sum;
count++;
}
}
}
Each inner loop you redeclare sum, effectively making it 0. You might want to move the declaration up one or two loops from the assignment depending on what you are trying to achieve.
Do you realise that you have two separate sets of variables named a, b and c? One is local to the function main, and the other is a static for the whole program. I suspect that this is not what you intended. Try deleting the one that is local to main.
Martyn
A few things I found while poking about in addition to the other issues noted previously:
What are you compiling this with? With VC++ 2010 it "works", as in it outputs non-zeroes, although it complains about the DWORD ThreadIds[num_of_thr]; array declaration with a non-constant array size (I just made num_of_thr a constant and commented out the cin to test it quickly).
Are you sure you are inputting a valid number of threads with cin >> num_of_thr; For example, if num_of_thr was 0 this would explain the zeroes output. A simple cout here for num_of_thr would be useful.
In your data initialization loop starting with for(int i = 0; i < num_of_thr/2; i++) { you are not correctly counting threads which will result in an array underflow or overflow. For example, if num_of_thr is 5 then num_of_thr/2 is 2 which results in initializing only the elements 0..3 leaving the last element uninitialized. An array underflow is technically ok although the later CloseHandle() call will fail when it tries to free an essentially random handle. If you enter a larger number of threads you will overflow all your arrays (try it with num_of_thr=10 for example).
If it still doesn't work try removing the threading to see if the threading or code itself is the source of the problem. For example, you can call the ThreadProc() function manually in a loop instead of from within threads. Either trace through the program with a debugger or output logs to stdout/file (which would also work in the threading model).
Instead of a random source matrix I would use a few fixed values at first with a known result. This will make it easier to determine if the code is actually computing the correct result.