How to compare grid rows and columns with user input? - c++

Alright, so I have this code which basically will prompt the user to enter a number and then according to that number the user entered, they will be asked (Please enter a number between 1 and 4)* the number the user chose. Then, their input will be compared to see if there is any match in the grid (rows and columns). Let me show you an example:
Please enter a number: 3
Please enter a number between 1 and 4: 2
Please enter a number between 1 and 4: 1
Please enter a number between 1 and 4: 2
Here is your grid:
(3x3 grid filled, since user entered 3, filled with random numbers)
4 2 4
3 1 1
4 3 3
Here is a sample of my code:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <time.h>
#include <ctime>
using namespace std;
double Atemp = 0;
double Utemp = 0;
double Working = 0;
double Total = 0;
char Answer = 'x';
int Umain;
void printGrid(int &Umain);
void fillIntArray(int array[], int size);
void reverseArray(int array[], int size);
void outputIntArray(int array[], int n);
void compareGrid(int &Atemp);
int main(){
int maxNum = 2;
int intArray[maxNum];
cout << "Please Enter numbers between 1 and 12: ";
cin >> Umain;
do{
if(Umain <=12){
fillIntArray(intArray, maxNum);
//outputIntArray(intArray, maxNum);
printGrid(Umain);
}
}while (Answer == 'y');
return 0;
}
void fillIntArray(int array[], int size){
do{
for (Utemp = Umain; Utemp > 0; Utemp--){
cout << "Please enter a number between 1 and 4: ";
cin >> Atemp;
if(Atemp <=4 && Atemp >=1){
for (int i = Atemp; i < Atemp; i++);
}else{
cout << "Not within limit \n";
}
}
}while (Answer == 'y');
}
void printGrid(int &Umain){
cout<<endl;
cout<<" ";
int i=1,j;
for(j = 0; j <= 4*Umain; j++){
if(j%4==2){
cout<<" ";
}
}
cout<<endl;
for(i = 0; i <= 2*Umain; i++){
for(j = 0; j <= 2*Umain; j++){
if(i%2==0){
if(j==0){
cout<<" ";
}
if(j%2==0){
cout<<" ";
}else{
cout<<"---";
}
}else{
if(j%2==0){
cout<<" | ";
}else cout<< (rand()%4+1);
}
}
if(i%2!=0){
cout<<" ";
}
cout<<endl;
}
cout<<" ";
for(j = 0, i = 1; j <= 4*Umain; j++){
if(j%4==2){
cout<< " ";
}
}
cout<<endl;
}
void compareGrid(int &Atemp){
}

For one thing, variable size arrays are not a part of C++. This part is wrong:
int maxNum = 2;
int intArray[maxNum];
Fix it by adding constexpr:
constexpr int maxNum = 2;
int intArray[maxNum];
Secondly, this part in general doesn't make sense and the semicolon at the end is really suspicions:
for (int i = Atemp; i < Atemp; i++); // why?
And assuming you have collected the user inputs in an array called Attempts of size 3, and intArray is the matrix of size 3x3, here's how you might compare attempts to the rows/columns of the so-called 2D array:
bool Contains() {
for (size_t iCol = 0; iCol != 3; ++iCol) {
for (size_t iRow = 0; iRow != 3; ++iRow) {
if(intArray[iCol][iRow] != Attempts[iRow]) {
return false;
}
}
}
return true;
}
Change places of iCol and iRow to check rows or columns

Related

Why does void sorting(int *[], int) result in "Unable to read memory"?

I am working on a program in C++ that uses dynamically allocate memory. The function int *getNumbers(int) works fine.
What I am trying to do now is take that information and then sort it. When I send it to void sorting(int *[], int) I do not get any error message, but a "Unable to read memory". This is happening at:
if (*(sort[index]) < *minElem) // Around line 122
I am not really new to sorting, but the working with Pointers. Why does it not run correctly?
#include <iostream> //preprocessor directive Pg. 28 and Ch. 1
#include <string> // Same
#include <cmath>
#include <iomanip>
#include <ctime>
#include <fstream>
#include <cstdlib>
#include <cctype>
#include <algorithm>
#include <vector>
using namespace std;
int *getNumbers (int);
void sorting (int *[], int); //function that I am looking into
//does not work
int main ()
{
int *numbers_2 = nullptr;
int *numbers = nullptr; //pointer that I use
int num;
cout << "How mamy numbers\t";
cin >> num;
while (num < 5 || num > 21) {
cout << "\nPlease try again - between 5 and 20\n";
cout << "How mamy num\t";
cin >> num;
}
numbers = getNumbers (num);
cout << "\nThe numbers are:\n";
for (int index = 0; index < num; index++) {
cout << numbers[index] << " ";
}
sorting (&numbers, num); //sorting function does not work
cout << "\nLet's try this again\n";
cout << "\nThe numbers are:\n";
for (int index = 0; index < num; index++) {
cout << numbers[index] << " ";
}
delete[] numbers;
delete[] numbers_2;
numbers = nullptr;
numbers_2 = nullptr;
cout << "\nFinally Done!!!";
cout << "\n\n";
system ("PAUSE");
return 0;
}
int *getNumbers (int num)
{
int *array_Num = nullptr;
array_Num = new int[num];
for (int index = 0; index < num; index++) {
cout << "Please enter " << index + 1 << " number\t";
cin >> array_Num[index];
}
return array_Num;
}
void sorting (int *sort[], int size)
{
int startScan, minIndex;
int *minElem;
for (startScan = 0; startScan < (size - 1); startScan++) {
minIndex = startScan;
minElem = sort[startScan];
for (int index = (startScan + 1); index < size; index++) {
if (*(sort[index]) < *minElem) //part that I had problems
{
minElem = sort[index];
minIndex = index;
}
}
sort[minIndex] = sort[startScan];
sort[startScan] = minElem;
}
}
Your problem is you are passing a pointer to array (pointer to pointer to int) to sorting where you should simply pass the array itself. E.g. remove the '&' in you call to sorting in main() and change the sorting function to:
void sorting (int *sort, int size)
{
int startScan, minIndex;
int minElem;
for (startScan = 0; startScan < (size - 1); startScan++) {
minIndex = startScan;
minElem = sort[startScan];
for (int index = (startScan + 1); index < size; index++) {
if (sort[index] < minElem) //part that I had problems
{
minElem = sort[index];
minIndex = index;
}
}
sort[minIndex] = sort[startScan];
sort[startScan] = minElem;
}
}
Example Use/Output
$ ./bin/array_sorting
How mamy numbers 4
Please try again - between 5 and 20
How mamy num 6
Please enter 1 number 9
Please enter 2 number 2
Please enter 3 number 12
Please enter 4 number 5
Please enter 5 number 1
Please enter 6 number 3
The numbers are:
9 2 12 5 1 3
Let's try this again
The numbers are:
1 2 3 5 9 12
Finally Done!!!

happyNr(i); not functioning as I understand it should do

Write a program with a function main () and selecting a menu of functions:
Generate a programming-random number generator data for lottery ticket / max 100 / with six-digit numbers and store them in an array
-Overwrite generated a new array and sort this array in ascending order and display output
-Counting and display output and numbers of all "happy" six digit lottery tickets /these numbers which sum of the first 3 digits is equal to the last three/
-Save in the array and display output sequence numbers of downloaded "lucky" lottery tickets
I have a problem with last two steps.Can you explain how to do it correctly?
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <iostream>
using namespace std;
int numbers;
int array[100];
void generator()
{
srand((unsigned)time(0));
for(int i = 0; i < 100; i++)
{
numbers = (rand() % 900000) + 100000;
array[i] = numbers;
cout << numbers << endl;
}
}
void sorted_list()
{
int i = 100, a, b, c;
for (a = 0; a < i - 1; a++)
{
for(b = 1; b < i; b++)
{
if (array[b] < array[b - 1])
{
c = array[b];
array[b]= array[b - 1];
array[b - 1]=c;
}
}
}
for (a = 0; a < i; a++)
{
cout << a << ": " << array[a] << "\n";
}
}
bool happyNr(int a){
if (a<100000 || a>999999) return false;
int half1=0, half2=0;
for (int i=0;i<6;i++){
if (i<3) {half1+=a%10; a=a/10;}
else {half2+=a%10; a=a/10;}
}
return half1==half2;
}
int menu()
{
int choice;
cout<<"\n_______________MENU_______________";
cout<<"\n 1. Generate random numbers";
cout<<"\n 2. Sorted array";
cout<<"\n 3. Happy numbers";
cout<<"\n 4. Exit";
do
{
cout<<"\n Choice: ";
cin>>choice;
}while(choice<1||choice>4);
return(choice);
}
int main()
{
int i;
do
{
i=menu();
switch(i)
{
case 1: generator();break;
case 2: sorted_list();break;
case 3: happyNr(i);break;
}
}
while(i!=4);
return 0;
}

BinarySearch function not working

I've got a menu that I've been working on, and everything now seems to work, except for the binary search function. I am entering the size of the array, filling the array, printing it, then sorting it with my chronological menu, and then when I do sequential search, it seems to work. However, binary search does not even return -1 to indicate that the number was not found, the program just stops. Suggestions? Thanks.
#include<iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int size=0; //global variable size
int a[100]; //global array
int getSize()
{
cout << "Array Size: ";
cin >> size;
return size;
cout << endl;
}
int sequentialSearch(int n)
{
for(int i=0;i<size;i++)
{
if(n==a[i])
{
return (i+1);
}
}
return -1;
}
int binarySearch(int n)
{
int low=0,high=size,mid;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==n)
{
return mid+1;
}
else if(a[mid]>n)
high=mid-1;
else if(a[mid]<n)
low=mid-1;
}
return -1;
}
void sort1()
{
int i, j;
for (i = 0; i < size-1; i++)
{
for (j = 0; j < size-i-1; j++)
if (a[j] > a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
void sort2()
{
int i, j, m;
for (i = 0; i < size-1; i++)
{
m = i;
for (j = i+1; j < size; j++)
{
if (a[j] > a[m])
m = j;
}
int temp=a[m];
a[m]=a[i];
a[i]=temp;
}
}
void printMenu()
{
cout<<"0. Exit\n";
cout<<"1.Get the size needed for todays use of the array \n";
cout<<"2.Fill an array with random numbers from 1-100 \n";
cout<<"3.Print the array with position numbers \n";
cout<<"4.Sort the array in ascending sequence \n";
cout<<"5.Sort the array in descending sequence \n";
cout<<"6.Sequential search of the array for a target\n";
cout<<"7.Binary search of the array for a target\n";
}
void printTheArray()
{
for(int i=0;i<size;i++)
{
cout<<a[i]<<" is at position :"<<i+1<<endl;
}
}
void fillWithRandom()
{
for(int i=0;i<size;i++)
{
int x=rand()%101;
a[i]=x;
}
}
void dispatch(int ch)
{
switch(ch)
{
case 1:cout<<"Size of array :"<<getSize() << endl;
break;
case 2:fillWithRandom();
break;
case 3: printTheArray();
break;
case 4:sort1();
break;
case 5:sort2();
break;
case 6:
{
cout<<"Enter the number you want to search\n";
int t;
cin>>t;
int res1=sequentialSearch(t);
if(res1!=-1)
cout<<"Found in position :"<<res1<<endl;
else if(res1==-1)
cout<<"Not Found \n";
break;
}
case 7:
{
cout<<"Enter the number you want to search\n";
int t;
cin>>t;
int res=binarySearch(t);
if(res!=-1)
cout<<"Found in position :"<<res<<endl;
else if(res==-1)
cout<<"Not Found \n";
break;
}
default:cout<<"wrong choice\n";
}
}
int main ()
{
printMenu();
int choice;
cout<<"Type in a choice"<<endl;
cin>>choice;
while(choice!=0)
{
dispatch(choice); // one big switch statement
printMenu();
cout<<"Type in a choice"<<endl;
cin>>choice;
}
cout << endl;
// wrap-up
cout << "This program is coded by Troy Wilms" << endl; // fill in your name
// stops the program to view the output until you type any character
return 0;
}
for example, if you try finding 4 in list {1, 3, 5}, low will be always 0 and high will be always 2. because of the code 'low = mid - 1' I think it should be changed to 'low = mid + 1'

Rectangle shape of numerics

for(int width=1; width<=5; width++) {
if(width <= 1) {
for(int width=1; width<=5; width++) {
cout<<" "<<width<<" ";
}
} else if(width<5) {
cout<< endl;
for(int width2=5; width2<=9; width2++) {
if(width2==5 || width2==9)
cout<<" "<<width2<<" ";
else
cout<< " ";
}
} else {
cout<< endl;
for(int width3=13; width3>=9; width3--) {
cout<<" "<<width3<<" ";
}
}
}
this code which I have posted above draws this shape
1 2 3 4 5
5 9
5 9
5 9
13 12 11 10 9
but I actually want my code to print it like this, I have tried a lot changing things but all in vain. so, I'm looking forward to you guys.
1 2 3 4 5
16 6
15 7
14 8
13 12 11 10 9
If you print something on the console, going back in lines and carriage returns will be very messy.
The trick is to seperate the problem in 3 stages:
stage1: print the top line, simple enough
stage2: print the largest number wrapping around, then print some empty space and finish with the number at the end, make sure to increment and decrement the numbers accordingly.
stage3: print the last line.
Here is the code for the algorithm I just described:
#include <iostream>
using namespace std;
int main()
{
const int width=6;
const int height=6;
int numberInFront=(height-1)*2 + (width-1)*2;
int numberAtTheEnd= width;
for(int i=1; i<width; ++i) cout<<i<<"\t"; //print top line
cout<<endl;
for(int i=0; i<height-1; ++i)
{
cout<<numberInFront<<"\t";
for(int j=0; j<width-3; j++) cout<<"\t"; //print inner space
cout<<numberAtTheEnd<<endl;
numberInFront--;
numberAtTheEnd++;
}
//print last line:
int counter = numberInFront;
while(counter!=numberAtTheEnd-1)
{
cout<<counter<<"\t";
counter--;
}
return 0;
}
It helps to avoid magic numbers in your code using #defines or const variables. This makes it more readable and more extensible. For example if you wanted to make a square that was 20x20, your code would require a complete rewrite!
Start from this working solution to implement this principle into your coding.
#include <iostream>
using namespace std;
#define SIDE 4
int main(){
int perimeter = SIDE * 4;
for(int width=0; width<=SIDE; width++)
{
if(width < 1) {
for(int width=0; width <= SIDE; width++) {
cout<<" "<<width + 1<<" ";
}
cout<< endl;
}
else if(width < SIDE)
{
cout<<" "<<perimeter - width + 1 << "\t\t" << (SIDE + width) + 1;
cout<< endl;
}
else
{
for(int width3 = perimeter - SIDE; width3 >= perimeter - 2 * SIDE; width3--) {
cout<<" "<<width3 + 1<<" ";
}
cout<< endl;
}
}
return 0;
}
Here is solution
int width =6;
int total = (width-1)*4;
for(int row=1; row <=width; row++)
{
if(row == 1 )
{
for(int pr=1; pr<=width; pr++)
{
cout<<" "<<pr<<" ";
}
cout<<"\n";
}
else if( row == width)
{
for(int pr=1; pr<=width; pr++)
{
cout<<" "<<(total-row-pr+3)<<" ";
}
}
else
{
for(int pr=1; pr<=width; pr++)
{
if(pr ==1 )
cout<<" "<<(total-row+2)<<" ";
else if(pr ==width)
cout<<" "<<(width+row-1)<<" ";
else
cout<<" "<<" "<<" ";
}
cout<<"\n";
}
}

C++ condesing this code

Ok so I've already simplified/condense it while keeping the functionality,but im only doing C++ for a month and a half.Was at 100 lines of code.Is it possible to declare the variable in the functions arguement and then call them without passing values into the arguemnets?
#include <iostream>
#include <windows.h>
using namespace std;
int primeCheck10 (int j)
{
int count=0;
cout<<"Enter a number between 1 and 10___";
cin>>j;
if(j<1 ||j>10)
{
cout<<"Invalid Value\n";
return 0;
}
for(int i=2; i<j; i++)
{
if(j%i==0)
{
count++;
break;
}
}
if(count==0)
cout<<"Prime number\n";
else
cout<<"Not a Prime number\n";
}
int primeCheck100(int j)
{
int count=0;
cout<<"Enter a number between 1 and 100___";
cin>>j;
if(j<1 || j>100){
cout<<"Invalid Value\n";
return 0;
}
for(int i=2; i<j; i++)
{
if(j%i==0)
{
count++;
break;
}
}
if(count==0)
cout<<"Prime number\n";
else
cout<<"Not a Prime number\n";
}
int checkPrime1000(int j)
{
int count=0;
cout<<"Enter a number between 1 and 1000___";
cin>>j;
if(j<1 || j>1000){
cout<<"Invalid Value\n";
return 0;
}
for(int i=2; i<j; i++)
{
if(j%i==0)
{
count++;
break;
}
}
if(count==0)
cout<<"Prime number\n";
else
cout<<"Not a Prime number\n";
}
int main ()
{
system("pause");
return 0;
}
Yes, you can condense all the prime checking into a single function pretty easily. I'd change the structure of the code to just check whether a given number is prime, and return a bool to indicate whether it is or not:'
bool isprime(int n) {
int limit = sqrt(n)+1; // only need to check up to sqrt(n)
if (n == 2)
return true;
if (n == 1 || n % 2 == 0) // check if it's 1 or even
return false;
for (int i = 3; i <= limit; i += 2) // not even -- only check odd numbers
if (n % i == 0)
return false;
return true;
}
Then the code to get input and display results would be separate:
void primecheck(int limit) {
std::cout << "Please enter a number between 1 and " << limit;
int j;
std::cin >> j;
if (j<1 || j > limit)
std::cerr << "Invalid value";
static char const *labels [] = { "Not a prime number\n", "Prime number\n" };
std::cout << labels[isprime(j)];
}
It wouldn't be terribly difficult to make it even shorter than this, but we're reaching the point where it would probably end up less readable if you did so.
If I have unserstood correctly you then you are asking about default arguments. For example
#include <iostream>
void f( int i = 10 )
{
std::cout << "i = " << i << std::endl;
}
int main()
{
f();
}
You could just make one method... and add a bounds
int primecheck(int value, int bounds){
int count=0;
cout <<"Enter a number between 1 and " << bounds << "___";
cin>>value;
if(j<1 || value>bounds){
cout<<"Invalid Value\n";
return 0;
}
for(int i=2; i<value/2; i++)
{
if(value%i==0)
{
count++;
}
}
if(count==0)
cout<<"Prime number\n";
else
cout<<"Not a Prime number\n";
return count;
}
This alg is prob not the best way to check for primes though. for instance for(int i=2; i<j/2; i++) in your loop with optimize it. For example 32, 6x6 = 32, 2x16 = 32, 4x8 = 32. The highest number that can be divisible to j or value is half of it because 1 isn't considered under divisibility so the lowest number would be 2. Which is half.