This is may code for 2D array. I will using it for Battleship game.
I want to ask, if its necessary to use a dynamic memory because I have two 2D array. Also I want to ask if anyone can tell my how to improve or fix my code
I'm not sure that I used the Class correct, but its my first time
enter code here
#include <iostream>
#include<array>
#include <string>
#include <stdlib.h>
#include <vector>
using namespace std;
class Board {
public:
int grid[15][15];
int initBoard(int A, int B)
{
int grid[A][B];
for(int col=0; col<A; col++) //Outer column loop
{
for(int row=0; row<B; row++) //Inner row loop
{
grid[col][row]=0;
}
}
}
void printBoard(int A, int B)
{
if (B == 10){
cout<<endl;
cout<<" ---{WELCOME TO THE BATTLESHIP}---\n"<<endl;
cout << " 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |" << endl << endl;
}
else if (B == 15){
cout<<endl;
cout<<" ---{WELCOME TO THE BATTLESHIP}---\n"<<endl;
cout << " 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10| 11| 12| 13| 14|" << endl << endl;
}
for(int i=0; i<A; i++) //column loop
{
for(int j=0; j<B; j++) //row loop
{
if(j==0)
{
if(i<=9){
cout << i << " " ; //print row number and spaces before new row
}
else if(i>=10){
cout << i << " " ;
}
}
grid[i][j]=0;
cout << grid[i][j] ;
if(j <= B)
{
cout << " | ";
}
}
cout << endl; //new line at end of column
}
cout << endl;
}
}:
int main(){
system("clear");
cout<<endl;
cout<<"***------GAME MENU------***"<<endl<<endl;
int b;
string name;
string surname;
cout<<" Choose Difficulty\n\n"<<" 1 for Easy\n"<<" 2 for
Hard\n"<<endl;
cout<<"***---------------------***"<<endl<<endl;
cout<<"Enter your name: ";
cin>>name;
cout<<"Enter your surname: ";
cin>>surname;
cout<<"Enter your choice -->";
cin>>b;
system("clear");
if (b==1){
Board easy;
easy.initBoard(10,10);
easy.printBoard(10,10);
cout<<endl;
}
else if(b==2){
Board hard;
hard.initBoard(15,15);
hard.printBoard(15,15);
cout<<endl;
}
return 0;
}
if its necessary to use a dynamic memory because I have two 2D array.
On my system, Ubuntu 17.10, each thread stack size is 8 MB (default). You need to figure out your per thread auto-var size, and if your grid is smaller, and enough size is left for max depth function calls, you will not need to use dynamic memory.
Generally, I would not resist using dynamic memory.
Because I have 2D array
The dimensionality has no impact. The grid (made with std::array) takes a fixed number of bytes, and the elements are back to back.
Related
I have this section of code for generating an array of randomly generated and sorted ints, but the nosearch cin quits the program. Calling Cin.ignore() & cin.clear() before and/or after this line does not correct this, no error message is shown, the program just quits as soon as I hit enter on that section. This is the only statement to do this.
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include "search.hpp" //a function called sarch is here, program quits before sarch is called.
using namespace std;
int main () {
srand(time(0));
int tenn;
int minrange;
int maxrange;
cout << "Enter the number of integers: ";
cin >> tenn;
cout << endl << "Enter the lower limit: ";
cin >> minrange;
cout << endl << "Enter the upper limit: ";
cin >> maxrange;
int *arr = new int(tenn*10);
for (int i = 0; i < tenn*10; i++){
*(arr+i) = (rand() % maxrange) + minrange;
}
cout << "list, unsorted: " << endl;
for (int i = 0; i < tenn*10; i++){
cout << *(arr+i) << " ";
}
cout << endl;
for (int i = 0; i < tenn*10; i++){
int low = i;
for (int j = i; j < tenn*10; j++){
if (*(arr+j) < *(arr+low)){
low = j;
}
}
int temp = *(arr+i);
*(arr+i) = *(arr+low);
*(arr+low) = temp;
}
cout << "sorted list: " << endl;
for (int i = 0; i < tenn*10; i++){
cout << *(arr+i) << " ";
}
cout << endl;
int nosearch;
cout << "Enter the number of values you wish to search for: " << endl;
//The next cin will fail
cin >> nosearch;
cout << "v";
//more code here...
I use a makefile to compile the code, and when I run it in terminal, this is what happens:
>./Needle.exe
Enter the number of integers: 2
Enter the lower limit: 0
Enter the upper limit: 10
list, unsorted:
9 4 6 2 4 5 2 9 1 4 7 8 3 4 9 4 6 7 9 9
sorted list:
1 2 2 3 4 4 4 4 4 5 6 6 7 7 8 9 9 9 9 9
Enter the number of values you wish to search for:
3
>
I can only assume something I did above triggered this error, which is why I included so much of the code.
I'm trying to make a Sudoku puzzle generator for a school project, and I have most of the coding and logic worked out for the program, it's just that the random number generator I'm using to assign values to the Sudoku grid are generating numbers far out of the appropriate range, and I can't quite figure out why it's not functioning appropriately.
Here's the code for the number generator:
int Sudoku::RNG(int range, int start){
int randNum;
randNum = (rand()%range+start);
return randNum;
}
I've also seeded with
srand(time(NULL));
at the very start of my main method.
And here's the code for the method which populates the Sudoku grid with numbers from the RNG() function:
void Sudoku::gridPopulate(int grid [9][9]){
Solution s;
int num;
bool safe;
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
do{
safe = false;
num= RNG(9,1);
if(s.rowCheck(grid, i, num)&& s.colCheck(grid, j, num) && s.gridCheck(grid, i, j, num)){
grid[i][j] = num;
cout << "Number entered into grid" << endl;
safe = true;
}
}while(safe);
}
}
Main Method:
int main()
{
//Program Start
srand(time(NULL));
int difficulty;
int choice;
int grid[9][9];
cout << "Welcome to my Sudoku puzzle generator! \nTest your mental muscles and see if you can solve the puzzle!" << endl;
//Puzzle Generator
Sudoku game;
game.gridPopulate(grid);
cout << "board populated"<< endl;
cout << "Successful board made" << endl;
game.displayBoard(grid);
}
Example of erroneous Sudoku board below (formatting is off because of the huge numbers, just ignore the dashes and vertical lines):
1 5013192 4981028 9 |20064 8 5 |1 2 3 |
2 8 5 4 |1995768265 0 2114351727 |28 7670880 7670908 |
3 1 7274056 7 |3 0 7670880 |4 6 7670880 |
-----------------4 6 7 2 |4199040 1 8 |7670912 -1196314433 4 |
5 1953657218 1 0 |5 4 32 |7 3 7274140 |
6 5 8 1953722109 |2 9 7670916 |7274116 4199040 4358512 |
-----------------7 0 1953722297 1 |9 1953787893 3 |7274204 4 8 |
8 1953722109 1953722083 8 |4199040 4199040 0 |9 7274160 2 |
9 3 1953746112 1198757840 |6 7274216 4 |4358512 7274368 4358606 |
-----------------
1 2 3 4 5 6 7 8 9
The number's it's giving me are sometimes very large, sometimes not. It's kinda baffling me at the moment, any help or advice would be greatly appreciated!
EDIT/UPDATE #1:
I've revised my gridPopulate code, and I've added in a few cout statements for troubleshooting. The method will now stay on each individual array element until it is populated, the main issue I'm running into now is that the code will get stuck in the do/while statement where the RNG() is occurring. I'm using the counter to track how many RNG iterations it goes through before passing a safe value into the grid. The problem is that the RNG is going through way too many iterations before happening to generate a safe value, sometimes thousands of iterations before moving on. At some point it will just get stuck endlessly generating random numbers without being able to move on.'
void Sudoku::gridPopulate(int grid [9][9]){
Solution s;
int num;
do{
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
int counter = 0;
do{
srand(time(NULL));
num = RNG(9,1);
counter++;
cout << "RNG attempts: " << counter << endl;
}while(!(s.rowCheck(grid, i, num)&& s.colCheck(grid, j, num) && s.gridCheck(grid, i, j, num)));
grid[i][j]=num;
cout << grid[i][j] << endl;
cout << "Row #: " << i << endl;
cout << "Col #: " << j << endl;
}//end j loop
displayBoard(grid);
}//end i loop
displayBoard(grid);
}while(!validityCheck(grid));
Here's my displayBoard method too, though I don't think it is correlated to the problem.
void Sudoku::displayBoard(int grid[9][9]){
/**********************************************************/
cout << " ----------------------" << endl;
for(int i=0; i<9;i++){
if(i==0)
cout << "1 | ";
if(i==1)
cout << "2 | ";
if(i==2)
cout << "3 | ";
if(i==3)
cout << "4 | ";
if(i==4)
cout << "5 | ";
if(i==5)
cout << "6 | ";
if(i==6)
cout << "7 | ";
if(i==7)
cout << "8 | ";
if(i==8)
cout << "9 | ";
for(int j=0;j<9;j++){
cout << grid[i][j] << " ";
if(j==2)
cout << "| ";
if(j==5)
cout << "| ";
if(j==8)
cout << "| ";
}
cout << endl;
if(i==2)
cout << " ------------------------" << endl;
if(i==5)
cout << " ------------------------" << endl;
if(i==8)
cout << " ------------------------" << endl;
}
cout << "\n";
cout << " 1 2 3 4 5 6 7 8 9 " << endl;
/**********************************************************/
}
Nothing wrong with the RNG function, all we need is debugging skills
## Try this to see what is the immediate value of the grid[i][j] ##
`void Sudoku::void gridPopulate(int grid[9][9])
{
Solution s;
int num;
bool safe;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
do {
safe = false;
num = RNG(9, 1);
if (s.rowCheck(grid, i, num) && s.colCheck(grid, j, num) && s.gridCheck(grid, i, j, num)) {
grid[i`enter code here`][j] = num;
//cout << "Number entered into grid" << endl;
safe = true;
}
} while (safe);
cout << grid[i][j] << " ";
}
cout << endl;
}
}`
I am writing a program to sort a user entered array. The following code takes 8 single digit integers to be entered and then put into an array.
#include <iostream>
#include <stdio.h>
using namespace std;
void printArray(int ary[], int n) {
cout << "The sequence you entered is as follows:" << endl;
for (int i=0; i<n; i++) {
cout << ary[i] << " ";
}
cout << "\n";
}
int main() {
using namespace std;
int nums[8];
cout << "Please enter 8 single digits between 1 and 9" << endl;
for(int k=0; k<8; k++) {
scanf("%d", &nums[k]);
}
printArray(nums, 8);
cout << endl;
return 0;
}
But when I input digits, only the first integer is pushed into the array with the rest being 0s.
For example, when the input is:
2,5,7,2,1,4,6,8. The output is: 2 0 0 0 0 0 0 0
The input syntax you should use is like that : 2 5 7 2 1 4 6 8.
or you can change the scanf("%d", &nums[k]); to scanf("%d,", &nums[k]); and now you can enter 2,5,7,2,1,4,6,8
Is there a way to condense five for-loops into one and have them display different variables and letters for each? Currently, I have one loop with five other loops and if/else to keep it condense, but this seems redundant and defeats the very purpose of making the loop.
So I decided to post the whole source code so people can understand what I am trying to get at more. This is a program that creates 100 random grades everytime it runs and I have to sort them, then display them. I am aware I could do 5 for loops, but I want to write code that is more condensed and efficient.
The hard part is writing a loop that can display 5 arrays consistently even though the size of the array changes every run.
#include <iostream>
#include <vector>
using namespace std;
int main(){
int grades[100];
int sizeA=0, sizeB=0, sizeC=0, sizeD=0, sizeF=0;
std::vector<int> gradeA, gradeB, gradeC, gradeD, gradeF;
srand(time(NULL));
for(int i = 0; i < 100; i++){
grades[i] = rand() % 100 + 1;
}
for(int i = 0; i < 100; i++){
if (grades[i] < 100 || grades[i] > 0){
if (grades[i]>=90)
gradeA.push_back(grades[i]);
else if (grades[i]>=70)
gradeB.push_back(grades[i]);
else if (grades[i]>=50)
gradeC.push_back(grades[i]);
else if (grades[i]>=20)
gradeD.push_back(grades[i]);
else if (grades[i])
gradeF.push_back(grades[i]);
} else {
cout << "uhh.. ";
return(0);
}
}
sizeA = gradeA.size();
sizeB = gradeB.size();
sizeC = gradeC.size();
sizeD = gradeD.size();
sizeF = gradeF.size();
/**toggle ? showgrades(gradeA, size) : (int?)null;**/
}
How about using a function to do the looping and call it with the required information
void printGrades(const std::vector<int>& grades, char level) {
cout << num << " " << level << " students: ";
for(int i = 0; i < grades.size(); i++){
cout << grades[i] << " ";
cout << endl;
}
So when you want to print them all:
printGrades(gradeA, 'A');
printGrades(gradeB, 'B');
printGrades(gradeC, 'C');
printGrades(gradeD, 'D');
printGrades(gradeF, 'F');
If I were you, I would create a class Student, and then a 2D array, where every row would represent the student's category, and the number of columns of a row, the number of students.
That could be represented as a fixed-sized array of size 5, where every cell would be a std::vector of class Student.
Minimal working example:
#include <iostream>
#include <vector>
using namespace std;
class Student {
public:
Student(int grade, char category) : grade(grade), category(category) {}
int getGrade(void) { return grade; }
char getCategory(void) { return category; }
private:
int grade; // 0, ..., 20
char category; // A, ..., F
};
int main(void) {
vector<class Student> std[5]; // cell 0 is for A students, ..., cel 4 is for F students
std[0].push_back({20, 'A'}); std[0].push_back({19, 'A'});
std[1].push_back({15, 'B'});
std[2].push_back({17, 'C'}); std[2].push_back({17, 'C'});
std[3].push_back({14, 'D'});
std[4].push_back({15, 'F'});
for (int i = 0; i < 5; ++i) {
if(std[i].size()) {
cout << std[i].size() << " " << std[i][0].getCategory() << " students: ";
for (auto& student : std[i]) {
cout << student.getGrade() << " ";
}
cout << endl;
}
}
return 0;
}
Output:
2 A students: 20 19
1 B students: 15
2 C students: 17 17
1 D students: 14
1 F students: 15
Appendix:
I understand that you want to make the code compact, but this:
for(int a = 0; a < sizeA; a++){
cout << gradeA[a] << " ";
} aS = 1; bS = 0; cout << endl;
is not cool, since it's not readable for the reader. I suggest you to change it to:
for(int a = 0; a < sizeA; a++){
cout << gradeA[a] << " ";
}
aS = 1;
bS = 0;
cout << endl;
since a reader expects to see no code after the closing curly bracket. That's a general statement.
can someone fix my code?
this is the result that should be showed when i input number 5 in c++
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
my result:
1
2 6
3 7 10
4 8 11 14
5 9 12 15 18
my code:
#include <iostream.h>
#include <conio.h>
#include <math.h>
void main()
{
int n,i,j;
cout<<"insert number"<<endl;
cin>>n;
for (i=1;i<=n;i++)
{
int y=1;
int g=1;
cout<<i<<" ";
for (j=1;j<=i-1;j++)
{
int x=n;
int b=i;
x--;
g--;
cout<<(x*y)+b+g<<" ";
y++;
}
cout<<endl;
}
getch ();
}
what did i do wrong?
sorry if my code messy i'm a c++ new learner.
You could it like this:
#include <iostream>
using namespace std;
int main()
{
int n , i ,j, sum;
cout << "masukkan bilanga" << endl;
cin >> n;
for(i = 0; i < n; i++)
{
cout << i + 1 << " ";
sum = i + 1;
for(j = 0; j < i; j++)
{
sum += n - 1 - j;
cout << sum << " ";
}
cout << endl;
}
return 0;
}
where the key point is that you want to print all the numbers, starting from 1, in a column-major manner, until a triangular n x n matrix is created.
Driven from the output, one can easily see that every element of the next column is what the current element is, plus n - 1, and that factor decreases by one as we advance to the right part of the matrix.
Try this code, hope this is what you need:
#include <iostream>
#include <string>
void printMatrix(int number);
void main()
{
int number = 1;
std::cout << "Enter a number: ";
std::cin >> number;
printMatrix(number);
}
void printMatrix(int number) {
std::cout << std::endl;
for (int i = 1; i <= number; i++) {
std::cout << i << " ";
int n = i;
for(int j = 1; j < i; j++) {
n += number - j;
std::cout << n << " ";
}
std::cout << std::endl;
}
}