#include <iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
int n,m,counter=0;;
cin>>n>>m;
char x[n][m];
int y[n][m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>x[i][j]; //array input
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
counter=0;
if(x[i][j]=='.') // searching for mines(*)
{
if (x[i][j-1]=='*')
counter++;
if (x[i][j+1]=='*')
counter++;
if (x[i-1][j]=='*')
counter++;
if (x[i+1][j]=='*')
counter++;
if (x[i+1][j-1]=='*')
counter++;
if (x[i+1][j+1]=='*')
counter++;
if (x[i-1][j-1]=='*')
counter++;
if (x[i-1][j+1]=='*')
counter++;
}
if(x[i][j]!='*')
y[i][j]=counter; // assign values
else
y[i][j]='*';
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(y[i][j]==42)
cout<<'*';
else
cout<<y[i][j]; // output numeric array
}
cout<<endl;
}
return 0;
}
This is Minesweeper code which has input like
4 4
*...
....
.*..
....
and output
*100
2210
1*10
1110
But the code's output is
*101
2210
1*10
1110
the zero on the top right turn into 1 What's making it do that ?
and is there an more easy way to search for the mines(*) without all the if conditions ?
You are reading beyond array's memory. While you're on lines 0..n-2, you're reading next line's chars, at line n-1 you're reading inaccessible memory.
You have to check that memory you access belongs to proper lines and are within array bounds.
I.e.
if (x[i][j+1]=='*')
What if j == m - 1?
if (x[i-1][j]=='*')
What if i == 0?
There are basically two fixes to this problem.
First, you can each time check that i, j are in bounds, say
if (j < m - 1 && x[i][j+1]=='*')
That will solve the problem, but is bad from code reuse perspective. I'd write a function, say
char get_at(char ** array, int i, int j, int n, int m)
{
if (i >= 0 && i < n && j >= 0 && j < m)
return array[i][j];
else
return '!';
}
This function returns '!' if indices are out of bounds, so it will not be interpreted as a mine.
I am trying to point something out in your code:
int main()
{
int n,m,counter=0;;
cin>>n>>m;
char x[n][m];
int y[n][m];
/**
* Minesweeper solving has always worked (if followed step-wise) is
* scanning the neihbouring 8 cells i.e.
* top(left,middle,right),side(left,right), and
* bottom(left,middle,right). You probably should try and follow this
* in your code so that any indexing issues can be avoided
*
*
* BTW - don't forget the corners/edges
*
*/
for(int i=0;i<n;i++) // This is a bit dangerous what if the index is -1?
{
for(int j=0;j<m;j++) // Same indexing issue here.
{
cin>>x[i][j];
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
counter=0;
if(x[i][j]=='.') // If current pos is '.'
{
if (x[i][j-1]=='*')
counter++;
if (x[i][j+1]=='*')
counter++;
if (x[i-1][j]=='*')
counter++;
if (x[i+1][j]=='*')
counter++;
if (x[i+1][j-1]=='*')
counter++;
if (x[i+1][j+1]=='*')
counter++;
if (x[i-1][j-1]=='*')
counter++;
if (x[i-1][j+1]=='*')
counter++;
}
if(x[i][j]!='*') // If current pos is ANYTHING but '*', may be you want ELSE_IF condition?
y[i][j]=counter;
else
y[i][j]='*';
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(y[i][j]==42)
cout<<'*';
else
cout<<y[i][j];
}
cout<<endl;
}
return 0;
}
Is that what you are actually thinking?
Related
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter the size of the array :";
cin>>n;
int A[n][n];
int y=n,k=1,p=0,i;
while(k<=n*n)
{
for(i=p;i < y;i++)
{
A[y-1][i]=k++;
}
for(i=y - 2;i > p;i--)
{
A[i][y-1]=k++;
}
for(i=y - 2;i > p;i--)
{
A[p][i]=k++;
}
for(i = p + 1;i < y; i++)
{
A[i][p]=k++;
}
p++;
y--;
}
if(!n%2)
{
A[(n+1)/2][(n+1)/2]=n*n;
}
for(i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<A[i][j]<<"\t";
}
cout<<endl;
}
return 0;
I need to do a spiral matrix the way like this > enter image description here.
It breaks on the last "for" cycle and just doesn't show anything;;; Still, it shows up if I'm replacing one of the loop's statements;; I would be grateful if you point me where's my mistake!
(this code is a modified one brought from here https://www.includehelp.com/cpp-programs/print-a-spiral-matrix.aspx)
There were simply some little mistakes on the bounds of the loops (the bounds of the spiral). Here is a slightly modified programme.
PS: Note that you should avoid to use VMA int A[n][n] which is C, not C++.
#include<iostream>
//using namespace std;
int main()
{
int n;
std::cout << "Enter the size of the array :";
std::cin >> n;
int A[n][n];
int y = n, k = 1,p = 0,i;
while(k<= n*n)
{
for(i=p;i < y;i++)
{
A[y-1][i]=k++;
}
for(i=y - 2;i >= p;i--)
{
A[i][y-1]=k++;
}
for(i = y - 2;i >= p;i--)
{
A[p][i]=k++;
}
for(i = p + 1;i < y-1; i++)
{
A[i][p]=k++;
}
p++;
y--;
}
if(!n%2)
{
A[(n+1)/2][(n+1)/2]=n*n;
}
for(i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
std::cout<<A[i][j]<<"\t";
}
std::cout << "\n";
}
return 0;
}
This is what I wrote so far, where did I go wrong?
#include <iostream>
using namespace std;
int main()
{
int x[5], count=0;
for (int i=0;i<5;i++)
cin>>x[i];
for (int i=0;i<5;i++)
{
for (int n=2;n<x[i];n++)
{
if (x[i]%n==0)
count++;
}
if (count==1)
cout<<x[i]<<" ";
}
}
Edit:
Many thanks to everyone that tried to help. The problem was that I had to int count in the loop so that it would start from 0 every time. Here's my new working code:
#include <iostream>
using namespace std;
int main()
{
int x[5];
for (int i=0;i<5;i++)
cin>>x[i];
for (int i=0;i<5;i++)
{ int count=0;
for (int n=2;n<=x[i];n++)
{
if (x[i]%n==0)
count++;
}
if (count==1)
cout<<x[i];
}
}
#include <iostream>
using namespace std;
int main()
{
int x[5], count=0;
for (int i=0;i<5;i++)
cin>>x[i];
for (int i=0;i<5;i++)
{
bool check = true;
for (int n=2;n<x[i];n++)
{
if (x[i]%n==0)
{
check = false;
break;
}
}
if (check)
cout<<x[i]<<" ";
}
}
For better complexity, change your nested for loop to :
for (int n=2;n<=sqrt(x[i]);n++)
Other way :
int main ()
{
for (int i=2; i<100; i++)
{
bool check=true;
for (int n=2; n*n<=x[i]; n++)
{
if (x[i] % n == 0)
{
check=false;
break;
}
}
if(check) cout << x[i] << " ";
}
return 0;
}
Here's my solution.
I basically assume all numbers are prime, but if I find them not to be prime I don't print them out.
int main() {
bool primeNumber;
int length = 0;
int x[5], count=0;
for (int i=0;i<5;i++){
length++;
cin>>x[i];
}
for (int i = 0; i < length; i++ )
{
primeNumber = true;
for (int j = 3; j <= x[i]/2; j += 2 )//Not necessary to check agains numbers higher than half the number you want to check
{
if (x[i] % j == 0)
{
primeNumber = false;
}
}
if(primeNumber){cout << "Primenumber: " << x[i] << endl;}
}
}
EDIT:
Here's a comment on your code
Let's say your array looks like this
{5,9,13,15, 17}
int main()
{
int x[5], count=0;
for (int i=0;i<5;i++)
cin>>x[i];
for (int i=0;i<5;i++)
{
for (int n=2;n<x[i];n++)
{
Here you loop from 2-4(2,3,4). It's only necessary to loop half the number you want to check. e.g. (x[i]/2), but you can do it like you have done here.
if (x[i]%n==0){
count++;}
When your number is 5 and you check agains n numbers This will produce 5%2=1,5%3=2,5%4=1. But 5 is a prime number and your code didn't manage to detect that.
}
if (count==1)
Let's say you did find that 5 is a prime above and you managed to increment count to 1. What happens when you find another prime number in your array e.g. 7. That will make count be equal to 2. But you only check against 1, so therefor your next prime number doesn't get printed because count will only be equal to 1 after the first prime number and not the rest.
cout<<x[i]<<" ";
}
}
Hopefully you understood my explanation. It always helps to go over your code by hand or debug mode and think what the code will do with different numbers.
All numers are divideable by itself. That will make all numbers prime if you try to divide numbers with themselves
I am trying to implement a simple merge sort for even number of elements using the following code :
#include <iostream>
using namespace std;
void merge(int arr1[10],int len1,int arr2[10],int len2,int arr3[10],int len3)
{
int i,j,k;
while(i<len1&&j<len2&&k<len3)
{
if(arr1[i]<arr2[j])
{
arr3[k] = arr1[i];
i++;k++;
}
else if(arr1[i]>arr2[j])
{
arr3[k] = arr2[j];
k++;
j++;
}
}
}
void mergeSort(int a[10],int n)
{
int arr1[10],arr2[10];
for(int i=0;i<n/2;i++)
{
arr1[i] = a[i];
}
for(int i=(n/2+1);i<n;i++)
{
arr2[i] = a[i];
}
mergeSort(arr1,n/2);
mergeSort(arr2,n/2);
merge(arr1,n/2,arr2,n/2,a,n);
}
int main() {
int arr[10],n;
cout << "Enter number of elements\n";
cin >> n;
cout<<"Enter elements\n";
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
mergeSort(arr, n);
cout<<"Sorted array is"<<endl;
for(int i=0;i<n;i++)
{
cout<<arr[i]<<endl;
}
return 0;
}
But I am getting a EXC_BAD_ACESS error on the opening brace of the mergeSort() method. I am new to Xcode and not sure on how to fix this. How do I fix this ?
Thanks !
You have forgot to initialize the int variables i, j, k to 0 (zero) in the function definition for merge(...).
void merge(int arr1[10],int len1,int arr2[10],int len2,int arr3[10],int len3)
{
// int i,j,k; // Not initialized.
int i = j = k = 0;
while(i<len1&&j<len2&&k<len3)
{
...
...
}
After Edit:
void mergeSort(int a[10],int n)
{
int arr1[10],arr2[10];
for(int i=0;i<n/2;i++)
{
arr1[i] = a[i];
}
// Here you are skipping the middle index.
// Let's say array is of length 10, then arr1 contains elements on index from 0 to 4 (5 elements),
// whereas arr2 contains elements on index from 6 to 9 (4 elements).
// 5th index element is missing.
// for(int i=(n/2+1);i<n;i++)
for(int i=(n/2);i<n;i++)
{
arr2[i] = a[i];
}
mergeSort(arr1,n/2);
mergeSort(arr2,n/2);
merge(arr1,n/2,arr2,n/2,a,n);
}
Hope it helps!
I wanted to make a pyramid like this:-
____*
___*_*
__*___*
_*_____*
*********
for n=5.
the lines are not underscores but spaces.
My try:-
#include <iostream.h>
void main()
{ int i,k,l,n;
cin>>n;
for(i=1; i<=n-1; i++)
{
for(k=1; k<=i; k++)
{if((k==n+i-1)||(k==n-i+1))
cout<<"*";
else
cout<<" ";
}
cout<<"\n";
}
for(l=1; l<=2*n-1; l++)
cout<<"*";
}
But the output comes as:-
__ *
_*
Note: This is a turbo c++ program.
UPDATE:
With some optimization and by taking n as row count instead of base width, we have something very simple:
void drawPyramid(const int &n) {
int b=2*n-1;
for (int i=b/2; i>=0; i--) {
for (int j=0;j<b-i; j++) {
if (i==0 || j==i || j==b-i-1) {
std::cout<<"*";
} else {
std::cout<<" ";
}
}
std::cout<<std::endl;
}
}
Old:
It was quite funny to do, but it works as well. My approach is to start a counter from the maximum width that the pyramid may have at the end, then divide the problem into two distinct steps:
Go to the first edge
Go to the second edge
It sure can be optimized but it will give you the idea:
int drawPyramid(const int &baseWidth, const char &edgeChar, const char &outsideChar, const char &insideChar) {
// test if base width allows to have a single char at the top of it
if (baseWidth%2==0) {
std::cout<<"Error in 'drawPyramid(const int &baseWidth)': Pyramid base width must be an odd number for the top to match"<<std::endl;
return 0;
}
for (int i=baseWidth; i>=0; i-=2) { // the first edge is initially far, then gets closer
int j=0;
// Go to first edge
while (j<i/2) {
std::cout<<outsideChar;
j++;
}
std::cout<<edgeChar;
if (i==1) { // at the bottom of the pyramid
for (int k=0; k<baseWidth-1; k++) {
std::cout<<edgeChar;
}
} else if (i<baseWidth) { // test if there is a second edge to reach
// Go to second edge
while (j<baseWidth-i/2-2) {
std::cout<<insideChar;
j++;
}
std::cout<<edgeChar;
}
// Done with the current line
std::cout<<std::endl;
}
return 1;
}
Hope this helps :)
modify your loop to this and it works
for(i=1; i<=n-1; i++)
{
for(k=1; k<i + n; k++) // greater range than previously to include whole triangle
{if((k==n+i-1)||(k==n-i+1)) // == instead of --
cout<<"*";
else
cout<<" ";
}
cout<<"\n";
}
for(l=1; l<=2*n-1; l++)
So it wrote a piece of code. It generates a sorted array of 100 random number between [-100,100]. It then finds all the pairs of number that adds to 10 by putting them into a result[].
However its not working as intended.
THe random number and sorting seems fine. Its just the finding pairs part.
Can anyone tell me where I did wrong? Any help is appreciated.
Thanks
#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main()
{
int array[100];
int result[100];
int totalPair;
srand((unsigned)time(0));
for(int i=0; i<100; i++){
array[i] = (rand()%200)+1;
array[i]=array[i]-100;
}
std::sort(array,array+100);
int i=0;
int j=99;
int totalPairs=0;
while (i<j && i!=j)
{
if (array[i]+array[j] == 10)
{
result[totalPairs*2] = array[i];
result[totalPairs*2+1] = array[j];
totalPairs++;
++i;
--j;
}
else
{
if (array[i]+array[j] > 10) //make sum smaller reduce J
{
--j;
}
if (array[i]+array[j] < 10) //make sum larger increase I
{
++i;
}
if (array[i]+array[j] == 0)
{
++i;
}
}
}
for(int a=0; a<100; ++a){
cout<<array[a]<<endl;
}
for(int a=0; a<100; ++a){
cout<<result[a]<<endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}