The original question was to create a triangle out of hashes like this:
########
######
####
##
I decided to split the triangle in half and create half of each shape. Right now I have the code to create this shape:
####
###
##
#
code:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main () {
for (int row = 1; row <= 4; row++) {
for (int hashNum = 1; hashNum <= 5 - row; hashNum++) {
cout << "#";
}
cout << endl;
}
}
However, I cannot figure out how to create the other half of the shape. Does anyone have any ideas?
Here is a very step-by-step way to do it. Note there are more elegant ways to do this, namely recursion comes to mind.
#include <iostream>
void DrawTriangle(unsigned int rows)
{
// Loop over the rows
for(unsigned int spaces = 0; spaces < rows; ++spaces)
{
// Add the leading spaces
for(unsigned int i = 0; i < spaces; ++i)
{
std::cout << ' ';
}
// Add the hash characters
for(unsigned int j = 0; j < (rows - spaces)*2; ++j)
{
std::cout << '#';
}
// Add the trailing spaces
for(unsigned int i = 0; i < spaces; ++i)
{
std::cout << ' ';
}
// Add a newline to complete the row
std::cout << std::endl;
}
}
int main() {
DrawTriangle(4);
return 0;
}
Output
########
######
####
##
Sure: treat the blank area as a triangle of spaces, and double the width of your current triangle.
First of all I would consider the parameters of your problem. You are trying to draw a triangle of n rows of height with ascii chars. Considering that you take off one char on each side of the row on the next line, the minimum width of the base of your triangle is 2*(n-1)+1. For example, if you have n=3:
#####
###
#
Doing it this way your triangle shape will be better, with only one '#' at the bottom. After that the program is more straightforward. you can make something like this:
#include <iostream>
using namespace std;
void DrawInvTri(unsigned int nrows)
{
unsigned int ncols= (nrows-1)*2+1;
for (int i=0; i<nrows; i++)
{
// Write spaces before tri
for (unsigned int j=0; j<i; j++)
cout << " ";
// Write actual tri chars
for (unsigned int k=i; k<(ncols - i); k++)
cout << "#";
// Next line
cout << endl;
}
}
int main()
{
DrawInvTri(5);
DrawInvTri(3);
DrawInvTri(4);
return(0);
}
Related
ive got the below code to print a pattern (attached below). However i'd like to just use one loop
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
cout<<"*";
}
for(int j=1;j<=n-i;j++){
if(j%2!=0){
cout<<"_";
}else{
cout<<".";
}
}
cout<<endl;
}
for(int i=1;i<n;i++){
for(int j=1;j<=n-i;j++){
cout<<"*";
}
for(int j=1;j<=i;j++){
if(j%2==0){
cout<<".";
}else{
cout<<"_";
}
}
cout<<endl;
}
}
when n = 5, heres the output.
*_._.
**_._
***_.
****_
*****
****_
***_.
**_._
*_._.
how do i just make this into one single loop
Try this and see how it does what you want to understand the step you did not find on your own:
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n*2-1; i++) {
if (i <= n)
{
for (int j = 1; j <= i; j++) {
cout << "*";
}
for (int j = 1; j <= n - i; j++) {
if (j % 2 != 0) {
cout << "_";
}
else {
cout << ".";
}
}
cout << endl;
}
else
{
for (int j = 1; j <= n*2 - i; j++) {
cout << "*";
}
for (int j = 1; j <= i-n; j++) {
if (j % 2 == 0) {
cout << ".";
}
else {
cout << "_";
}
}
cout << endl;
}
}
}
I'd like to just use one loop.
I'll take it literally and show a starting point for a possible solution.
// Let's start by figuring out some dimensions.
int n;
std::cin >> n;
int height = 2 * n - 1;
int area = n * height;
// Now we'll print the "rectangle", one piece at a time.
for (int i = 0; i < area; ++i)
{ // ^^^^^^^^
// Extract the coordinates of the char to be printed.
int x = i % n;
int y = i / n;
// Assign a symbol, based on such coordinates.
if ( x <= y and x <= height - y - 1 )
{ // ^^^^^^ ^^^^^^^^^^^^^^^^^^^ Those are the diagonals.
std::cout << '*'; // This prints correctly the triangle on the left...
}
else
{
std::cout << '_'; // <--- But of course, something else should done here.
}
// End of row.
if ( x == n - 1 )
std::cout << '\n';
}
If you look at the pattern, then you can see a sort of "triangles". And this already gives a hint for the solution. Use a triangle function.
Please read about it here.
Then you will notice that always the "aboslute"-function, in C++ std::abs, is involved.
But first of all, it is easily visible that the number rows to print is always the width of a triangle * 2.
And the number of charcters in the pattern, can be calculated by applying the triangle function. Example for width 5:
Number of stars number of dashdot
Row width-abs(row-width) abs(row-width)
1 1 4
2 2 3
3 3 2
4 4 1
5 5 0
6 4 1
7 3 2
8 2 3
9 1 4
And this can be implemented easily now.
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std::string_literals;
int main() {
// Get the max width of the pattern and perform a short input validation
int maxWidth{};
if ((std::cin >> maxWidth) and (maxWidth > 0)) {
// The number of rows for the pattern is dependent on the width. It is a simple relation
const int numberOfRows = 2 * maxWidth;
// Show all rows
for (int row = 1; row < numberOfRows; ++row) {
// Use triangle formular to create star pattern
std::string starPattern(maxWidth - std::abs(row - maxWidth), '*');
// Create dashDot pattern
std::string ddp(std::abs(row - maxWidth), '\0');
std::generate(ddp.begin(), ddp.end(), [i = 0]() mutable { return i++ % 2 ? '.' : '_'; });
// Show output
std::cout << (starPattern+ddp) << '\n';
}
}
else std::cout << "\n*** Error: Invalid input\n\n";
}
Of course you can also create the whole pattern wit std::generate.
Maybe it is too complex for now.
And less understandable.
See:
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <vector>
int main() {
// Get the max width of the pattern and perform a short input validation
if (int width{}; (std::cin >> width) and (width > 0)) {
std::vector<std::string> row(2 * width - 1);
std::for_each(row.begin(), row.end(), [&, r = 1](std::string& s) mutable {
s = std::string(width - std::abs(r - width), '*');
std::string ddp(std::abs(r++ - width),'\0');
std::generate(ddp.begin(), ddp.end(), [&, i = 0]() mutable{ return i++ % 2 ? '.' : '_'; });
s += ddp; std::cout << s << '\n'; });
}
else std::cout << "\n*** Error: Invalid input\n\n";
}
i want this code can show:
1 2 3 .... 10
1 * *
2 #
.
. *
10 *
#include <iostream>
#include <iomanip>
#include <time.h>
int coordinates[1][10] = { 1,2,3,4, 5,6,7,8,9,10 };
for (int k = 0; k < 1; k++) {
for (int j = 0; j < 10; j++) {
cout << " " << coordinates[k][j];
}
cout << endl;
}
for (int r = 0; r < 1; r++) {
for (int s = 0; s < 10; s++) {
cout << coordinates[r][s] << endl;
}
}
return 0;
}
I want put sign# in position(3,2), LIKE THE ABOVE
and also put some points(*) into coordinate system randomly, and the points cannot be put them at 8 immediate neighbors of #position(3,2)
My suggestion is to make a 2d array of characters:
char board[MAX_ROWS][MAX_COLUMNS] = {0};
A better improvement is to use an extra column for the newline character:
char board[MAX_ROWS][MAX_COLUMNS + 1] = {0};
for (unsigned int i = 0U; i < MAX_ROWS; ++i)
{
board[i][MAX_COLUMNS] = '\n';
}
The extra column allows you to print the board with one statement:
std::cout << board << "\n";
If you want fancies, you can set up the output attributes before printing:
std::cout.width(3); // each cell is 3 wide
std::cout.fill(' '); // Pad each cell with spaces.
std::cout << board << "\n";
You can also add an extra column for displaying the row numbers and an extra row for display column numbers.
Edit 1: Setting a point
Setting a point is simple:
board[row][column] = '*'; // Set a point.
board[x][y] = ' '; // Erase a point.
Since the board is of type char, you can use different characters as points, such as '-', '+', 'M', etc.
I successfully made a connect 4 board that allowed two players to face one another and got it all working. But now I am trying to an AI to it but I'm having an issue that I'm unable to resolve.
Essentially I am wanting the AI to get all of the game squares in my 9x9 grid that are empty but have square underneath them which is not empty - as are the rules of connect 4.
Because my grid is a two dimensional vector, I imagine that the choice of movement for the AI would be 8 possible positions - because that's the width of the board. I am trying to save 8 possible positions - for example board[4][6], [board[5][6] - and then have the AI randomly select a position to spawn on.
Sorry if that's a really unclear explanation, I find it really to portray my intentions with programming.
I have some code that somewhat achieves this by spawning a game piece on top of an existing game piece but of course I am hoping to somehow store these coordinates and then have the AI randomly choose one position.
Thank you so much for your time.
// AiOnBoard.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
namespace game
{
const char EMPTY = ' ';
}
void spawn(std::vector<std::vector<char>>& board)
{
int i = 0;
for (int row = 0; row < 9; row++)
{
for (int col = 0; col < 9; col++)
{
if(board[row][col] == game::EMPTY)
{
int tempRow = row;
if(tempRow < 8) //So it doesn't exceed the bounds of the vector.
tempRow++;
if (board[tempRow][col] != game::EMPTY)
{
//std::cout << "Row: " << row << ". Col: " << col << "\n";
board[row][col] = 'O';
//return;
}
}
}
}
}
void displayBoard(const std::vector<std::vector<char>> board)
{
for (int row = 0; row < 9; row++)
{
std::cout << "\t";
for (int col = 0; col < 9; col++)
{
std::cout << "|" << board[row][col] << "|";
}
std::cout << "\n";
}
}
void initBoard(std::vector<std::vector<char>>& board)
{
std::vector<char> tempBoard;
for (int i = 0; i < 9; i++)
{
tempBoard.push_back(game::EMPTY);
}
for (int i = 0; i < 9; i++)
{
board.push_back(tempBoard);
}
}
int main()
{
std::vector<std::vector<char>> board;
initBoard(board);
board[5][4] = 'X';
board[5][2] = 'X';
board[4][6] = 'X';
spawn(board);
displayBoard(board);
char c;
std::cin >> c;
}
It's been a long time since I've used C++, so please forgive any errors in the code.
Basically, what you seem to be looking for is a vector containing all of the possible moves that can be made. You pretty much have that in your code already. You find the spots that can be moved into, now you just need to store that in a vector.
void findMoves(std::vector<std::vector<char>>& board)
{
std::vector<int> moves;
for (int col = 0; col < 9; col++)
{
bool found = false;
for (int row = 8; row >= 0; row--)
{
// find the first empty spot from the bottom up
if (board[row][col] == game::EMPTY)
{
moves.push_back(row);
found = true;
break; // don't check the rest of the column
}
}
if (!found)
{
moves.push_back(-1); // the column is full to the top
}
}
// now you have all the available moves
// you can analyze these moves in this function or
// change the function from void to vector<int> and
// return moves so it can be passed to another function
}
Note that I've swapped the loops so that it checks column by column instead of row by row, and checks the rows from the bottom up to save time.
I have no idea why ios::right works once. totally nothing
Same problem with ios::hex, ios::decimal and a few others unless I do some insane codes and get them magically work again
#include <iostream>
#include <iomanip>
using std::cout;
using std::ios;
int main() {
int len;
std::cin >> len;
// w = len + 1;
cout.width(len);
cout.setf(ios::right);
for (int s = 0; s < len; s++) {
for (int c = 0; c <= s; c++) {
cout << '#';
}
cout << '\n';
}
std::cin.get();
std::cin.get();
}
Expected Output:
#
##
###
####
#####
######
What i get:
#
##
###
####
#####
######
Tried This:
cout << ios::right << '#';
Didn't work.
You need to write cout.width(len-s);cout.setf(ios::right); inside the first loop because ios::right works only for one time. So it should be
#include <iostream>
#include <iomanip>
using std::cout;
using std::ios;
int main()
{
int len;
cin >> len;
for (int s = 0; s < len; s++)
{
cout.width(len);
cout.setf(ios::right);
for (int c = 0; c <= s; c++)
{
cout<<"#";
}
cout<<"\n";
}
std::cin.get();
std::cin.get();
}
But your code is not correct as per you required output , correct code is :
#include <iostream>
#include <iomanip>
using std::cout;
using std::ios;
int main()
{
int len;
cin >> len;
for (int s = 0; s < len; s++)
{
cout.width(len-s); // to align properly
cout.setf(ios::right);
for (int c = 0; c <= s; c++)
{
cout<<"#";
}
cout<<"\n";
}
std::cin.get();
std::cin.get();
}
The problem here is not that right is temporary, but that the width is temporary, so the next character being output does not use the width given - in fact that's a good thing, or your second line would be # #, so you probably don't want that!
The solution is to move the width call into the outer of your two loops (and recalculated the width accordingly as you get wider and wider output).
I'm intentionally not writing how you should do this, as you need to practice thinking about how thing work, not practicing CTRL-C/CTRL-V.
A shorter and simpler way of doing what you want
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; ++i) {
for (int j = n; j > 0; --j)
cout << (i >= j ? "#" : " ");
cout << endl;
}
return 0;
}
Input
6
Output
#
##
###
####
#####
######
See http://ideone.com/fbrfpe demo.
Hello guys I just want to ask how can I create a triangle using c++?
Actually I have my code but I don't have an idea how to center the first asterisk in the triangle. My triangle is left align. How can I make it a pyramid?
Here's my code below.
#include<iostream>
using namespace std;
int main(){
int x,y;
char star = '*';
char space = ' p ';
int temp;
for(x=1; x <= 23; x++){
if((x%2) != 0){
for(y=1; y <= x ; y++){
cout << star;
}
cout << endl;
}
}
return 0;
}
For a triangle och height Y, then first print Y-1 spaces, followed by an asterisk and a newline. Then for the next line print Y-2 spaces, followed by three asterisks (two more than previously printed) and a newline. For the third line print Y-3 spaces followed by five asterisks (again two more than previous line) and a newline. Continue until you have printed your whole triangle.
Something like the following
int asterisks = 1;
for (int y = HEIGHT; y > 0; --y, asterisks += 2)
{
for (int s = y - 1; s >= 0; --s)
std::cout << ' ';
for (int a = 0; a < asterisks; ++a)
std::cout << '*';
std::cout << '\n';
}
To calculate the number of spaces needed to center each row use this algorithm:
numSpaces = (23 - x) / 2;
and then a for loop to apply the spaces numSpaces times.
Here is the complete code:
#include<iostream>
using namespace std;
int main(){
int x,y;
char star = '*';
char space = ' p ';
int temp;
int numSpaces = 0;
for(x=1; x <= 23; x++){
if((x%2) != 0){
numSpaces = (23 - x) / 2; // Calculate number of spaces to add
for(int i = 0; i < numSpaces; i++) // Apply the spaces
{
cout << " ";
}
for(y=1; y <= x ; y++){
cout << star;
}
cout << endl;
}
}
return 0;
}
And the output:
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
***********************
One way to do
this is to nest two inner loops, one to print spaces and one to print *(s), inside an outer
loop that steps down the screen from line to line.
#include <iostream>
using namespace std;
int main(){
int row = 5;
for(int i=0; i<row; i++){
for(int j=row; j>i; j--){
cout << " ";
}
for(int k=0; k<2*i+1; k++){
cout << "*";
}
cout << endl;
}
return 0;
}
Output:
*
***
*****
*******
*********
This code is in C#, but you can convert it in c++.
class Program
{
static void Main()
{
int n = 5; // Number of lines to print.
for(int i = 1; i<= n; i++){
//loop for print space in the order (4,3,2,1,0) i.e n-i;
for(int j= 1; j<= n-i; j++){
Console.Write(" ");
}
//loop for print * in the order (1,3,5,7,9..) i.e 2i-1;
for(int k= 1; k<= 2*i-1; k++){
Console.Write("*");
}
Console.WriteLine(); // Next Line.
}
}
}
Here's another solution that doesn't use division or if statements
#include <iostream.h>
int main() {
int height = 17, rowLength, i, j, k;
char symbol = '^';
// print a pyramid with a default height of 17
rowLength = 1;
for (i = height; i > 0; i--) { // print a newline
cout << endl;
for (j = 1; j <= i; j++) // print leading spaces
cout << " ";
for (k = 0; k < rowLength; k++) // print the symbol
cout << symbol;
rowLength = rowLength + 2; // for each row increase the number of symbols to print
}
cout << "\n\n ";
return 0;
}
Star pyramid using for loop only:-
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
int n;
cout << "enter the number of rows of pyramid you want : ";
cin >> n;
"\n";
for (int i = 0; i <= n; ++i) {
cout << "\n";
for (int j = 0; j <= n - i; ++j) {
cout << " ";
}
for (int k = 1; k <= i; k++) {
cout << setw(3) << "*";
}
}
return 0;
}
I did that using two loops
here is my code
#include <iostream>
#include <string>
using namespace std;
int main() {
int rows, star, spaces;
int number_of_stars = 5;
int number_of_rows = number_of_stars;
string str1 = "*";
for (rows=1; rows <= number_of_rows; rows++) {
for (spaces=1; spaces <= number_of_stars; spaces++) {
if (spaces==number_of_stars)
{
cout<<str1;
str1+="**";
}
else
cout<<(" ");
}
cout<<("\n");
number_of_stars = number_of_stars - 1;
}
return 0;
}
and the result is
*
***
*****
*******
*********
Url of code on Online compiler
and you can solve it using only one loop, its simple and easy
#include <iostream>
#include <string>
using namespace std;
int main()
{
int numberOfLines=4;
string spaces=string( numberOfLines , ' ' );//this is 4 spaces
string stars="*";
while(spaces!="")
{
cout<<spaces<<stars<<endl;
spaces = spaces.substr(0, spaces.size()-1);
stars+="**";
}
}
Url of code on Online compiler
#include<iostream>
using namespace std;
int for1(int &row);//function declaration
int rows;//global variable
int main()
{
cout<<"enter the total number of rows : ";
cin>>rows;
for1(rows);//function calling
cout<<"just apply a space at the end of the asteric and volla ";
}
int for1(int &row)//function definition
{
for(int x=1;x<=row;x++)//for loop for the lines
{
for(int y=row;y>=x;y--) //for loop for spaces (dynamic loop)
{
cout<<" ";
}
for(int k=1;k<=x*2-x;k++)//for loop for asteric
{
cout<<"* ";/*apply a space and you can turn a reverse right angle triangle into a pyramid */
}
cout<<endl;
}
}