Hi i am new to programming and i currently have this code:
namespace Patterns
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 4; i++)//'rows'
{
for (int h = 1; h <= 9 - (i*2)+1; h++)
{
Console.Write("#");
}
Console.WriteLine("\n" );
}
}
}
}
This produces this output:
########
######
####
##
the number of hashes is correct as i am going from 8, 6, 4, 2 but i need to add an extra space every time i go onto a new line. How do i make it so the output is as follows?
########
######
####
##
Thanks,
Umer
From your code you could modify it to do the following in the inner for loop:
for (int j = 0; j < i - 1; j++) {
Console.Write(" ");
}
for (int h = 1; h <= 9 - (i*2)+1; h++) {
Console.Write("#");
}
Console.WriteLine("\n" );
As a note you should probably use StringBuilder to do this as I believe it is quite inefficient to constantly call Console.WriteLine.
The code could be modified further:
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 4; i++) {
for (int j = 0; j < i - 1; j++) {
sb.append(" ");
}
for (int h = 1; h <= 9 - (i*2)+1; h++) {
sb.append("#");
}
sb.append("\n" );
}
Console.WriteLine(sb.toString());
Introduce variables, start your rows at 0 and repeat the string for each row number.
This can also be applied to the string printing the hashes:
static void Main(string[] args)
{
int rows = 4;
int columns = 9;
for (int i = 0; i < rows; i++)
{
// Print a string with `i` spaces.
Console.Write(new String(' ', i));
int hashes = columns - ((i + 1) * 2) + 1;
Console.Write(new String('#', hashes));
Console.WriteLine();
}
}
Basically, just add space in front of your hash characters.
######## Row 1 (i=1), 0 Space
###### Row 2 (i=2), 1 Space
#### Row 3 (i=3), 2 Spaces
## Row 4 (i=4), 3 Spaces
In this case, you need "i-1" spaces for each rows. (Actually, it's (8 - charater count) / 2) and character count was 9 - (i*2) + 1, so ( 8 - 9 + i * 2 - 1 ) / 2 = (i * 2 - 2) / 2 = i - 1 )
So just make loop to add spaces before print hash chracters.
namespace Patterns
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 4; i++)//'rows'
{
for (int j = 0; j < i -1; j++) {
Console.Write(" ");
}
for (int h = 1; h <= 9 - (i*2)+1; h++)
{
Console.Write("#");
}
Console.WriteLine("\n" );
}
}
}
}
You could do something like this:
for (int i = 1; i <= 4; i++)//'rows'
{
for (int h = 1; h <= 9 - (i*2)+1; h++)
{
Console.Write("#");
}
Console.WriteLine("\n" );
for (int y = i; y > 0; y--)
{
Console.Write(" ");
}
}
Related
I want to print the following pattern:-
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
But I am getting the following output:-
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Here is the Code:
static void Main(string[] args)
{
int spacelimit = 13, num = 1, n = 5;
for(int i = 1; i<=n; i++)
{
for (int space = spacelimit; space >= i; space--)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write("{0,3:D} ",num++);
}
spacelimit = spacelimit - 3;
Console.WriteLine();
}
Console.ReadKey();
}
What I am doing wrong with the spaces? I am unable to do it.
This will do the trick
int spacelimit = 13, num = 1, n = 5;
for(int i = 1; i <= n; i++)
{
for(int space = spacelimit; space >= i; space--)
{
Console.Write(" ");
}
for(int k = 1; k <= i; k++)
{
Console.Write("{0,2:D} ", num++);
}
spacelimit = spacelimit - 2;
Console.WriteLine();
}
Console.ReadKey();
I have just changed 3 to 2 i.e. spacelimit - 2 and {0,2:D}
Yes changing spacelimit also solves the issue with trailing spaces but this solution worked as expected ... please have a look on the image.
If we make space>= i-3 in for loop, as shown below, it works fine. Please check. Thanks.
int spacelimit = 13, num = 1, n = 5;
for (int i = 1; i <= n; i++)
{
for (int space = spacelimit; space >= i - 3; space--) // HERE, I MADE i-3
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write("{0,3:D} ", num++);
}
spacelimit = spacelimit - 3;
Console.WriteLine();
}
Console.ReadKey();
Set the initial value of spacelimit to 16.
I come looking for general tips about the program I'm writing now.
The goal is:
Use neural network program to recognize 3 letters [D,O,M] (or display "nothing is recognized" if i input anything other than those 3).
Here's what I have so far:
A class for my single neuron
public class neuron
{
double[] weights;
public neuron()
{
weights = null;
}
public neuron(int size)
{
weights = new double[size + 1];
Random r = new Random();
for (int i = 0; i <= size; i++)
{
weights[i] = r.NextDouble() / 5 - 0.1;
}
}
public double output(double[] wej)
{
double s = 0.0;
for (int i = 0; i < weights.Length; i++) s += weights[i] * wej[i];
s = 1 / (1 + Math.Exp(s));
return s;
}
}
A class for a layer:
public class layer
{
neuron[] tab;
public layer()
{
tab = null;
}
public layer(int numNeurons, int numInputs)
{
tab = new neuron[numNeurons];
for (int i = 0; i < numNeurons; i++)
{
tab[i] = new neuron(numInputs);
}
}
public double[] compute(double[] wejscia)
{
double[] output = new double[tab.Length + 1];
output[0] = 1;
for (int i = 1; i <= tab.Length; i++)
{
output[i] = tab[i - 1].output(wejscia);
}
return output;
}
}
And finally a class for a network
public class network
{
layer[] layers = null;
public network(int numLayers, int numInputs, int[] npl)
{
layers = new layer[numLayers];
for (int i = 0; i < numLayers; i++)
{
layers[i] = new layer(npl[i], (i == 0) ? numInputs : (npl[i - 1]));
}
}
double[] compute(double[] inputs)
{
double[] output = layers[0].compute(inputs);
for (int i = 1; i < layers.Length; i++)
{
output = layers[i].compute(output);
}
return output;
}
}
Now for the algorythm I chose:
I have a picture box, size 200x200, where you can draw a letter (or read one from jpg file).
I then convert it to my first array(get the whole picture) and 2nd one(cut the non relevant background around it) like so:
Bitmap bmp2 = new Bitmap(this.pictureBox1.Image);
int[,] binaryfrom = new int[bmp2.Width, bmp2.Height];
int minrow=0, maxrow=0, mincol=0, maxcol=0;
for (int i = 0; i < bmp2.Height; i++)
{
for (int j = 0; j < bmp2.Width; j++)
{
if (bmp2.GetPixel(j, i).R == 0)
{
binaryfrom[i, j] = 1;
if (minrow == 0) minrow = i;
if (maxrow < i) maxrow = i;
if (mincol == 0) mincol = j;
else if (mincol > j) mincol = j;
if (maxcol < j) maxcol = j;
}
else
{
binaryfrom[i, j] = 0;
}
}
}
int[,] boundaries = new int[binaryfrom.GetLength(0)-minrow-(binaryfrom.GetLength(0)-(maxrow+1)),binaryfrom.GetLength(1)-mincol-(binaryfrom.GetLength(1)-(maxcol+1))];
for(int i = 0; i < boundaries.GetLength(0); i++)
{
for(int j = 0; j < boundaries.GetLength(1); j++)
{
boundaries[i, j] = binaryfrom[i + minrow, j + mincol];
}
}
And convert it to my final array of 12x8 like so (i know I could shorten this a fair bit, but wanted to have every step in different loop so I can see what went wrong easier[if anything did]):
int[,] finalnet = new int[12, 8];
int k = 1;
int l = 1;
for (int i = 0; i < finalnet.GetLength(0); i++)
{
for (int j = 0; j < finalnet.GetLength(1); j++)
{
finalnet[i, j] = 0;
}
}
while (k <= finalnet.GetLength(0))
{
while (l <= finalnet.GetLength(1))
{
for (int i = (int)(boundaries.GetLength(0) / finalnet.GetLength(0)) * (k - 1); i < (int)(boundaries.GetLength(0) / finalnet.GetLength(0)) * k; i++)
{
for (int j = (int)(boundaries.GetLength(1) / finalnet.GetLength(1)) * (l - 1); j < (int)(boundaries.GetLength(1) / finalnet.GetLength(1)) * l; j++)
{
if (boundaries[i, j] == 1) finalnet[k-1, l-1] = 1;
}
}
l++;
}
l = 1;
k++;
}
int a = boundaries.GetLength(0);
int b = finalnet.GetLength(1);
if((a%b) != 0){
k = 1;
while (k <= finalnet.GetLength(1))
{
for (int i = (int)(boundaries.GetLength(0) / finalnet.GetLength(0)) * finalnet.GetLength(0); i < boundaries.GetLength(0); i++)
{
for (int j = (int)(boundaries.GetLength(1) / finalnet.GetLength(1)) * (k - 1); j < (int)(boundaries.GetLength(1) / finalnet.GetLength(1)) * k; j++)
{
if (boundaries[i, j] == 1) finalnet[finalnet.GetLength(0) - 1, k - 1] = 1;
}
}
k++;
}
}
if (boundaries.GetLength(1) % finalnet.GetLength(1) != 0)
{
k = 1;
while (k <= finalnet.GetLength(0))
{
for (int i = (int)(boundaries.GetLength(0) / finalnet.GetLength(0)) * (k - 1); i < (int)(boundaries.GetLength(0) / finalnet.GetLength(0)) * k; i++)
{
for (int j = (int)(boundaries.GetLength(1) / finalnet.GetLength(1)) * finalnet.GetLength(1); j < boundaries.GetLength(1); j++)
{
if (boundaries[i, j] == 1) finalnet[k - 1, finalnet.GetLength(1) - 1] = 1;
}
}
k++;
}
for (int i = (int)(boundaries.GetLength(0) / finalnet.GetLength(0)) * finalnet.GetLength(0); i < boundaries.GetLength(0); i++)
{
for (int j = (int)(boundaries.GetLength(1) / finalnet.GetLength(1)) * finalnet.GetLength(1); j < boundaries.GetLength(1); j++)
{
if (boundaries[i, j] == 1) finalnet[finalnet.GetLength(0) - 1, finalnet.GetLength(1) - 1] = 1;
}
}
}
The result is a 12x8 (I can change it in the code to get it from some form controls) array of 0 and 1, where 1 form the rough shape of a letter you drawn.
Now my questions are:
Is this a correct algorythm?
Is my function
1/(1+Math.Exp(x))
good one to use here?
What should be the topology? 2 or 3 layers, and if 3, how many neurons in hidden layer? I have 96 inputs (every field of the finalnet array), so should I also take 96 neurons in the first layer? Should I have 3 neurons in the final layer or 4(to take into account the "not recognized" case), or is it not necessary?
Thank you for your help.
EDIT: Oh, and I forgot to add, I'm gonna train my network using Backpropagation algorythm.
You may need 4 layers at least to get accurate results using back propagation method. 1 input, 2 middle layers, and an output layer.
12 * 8 matrix is too small(and you may end up in data loss which will result in total failure) - try some thing 16 * 16. If you want to reduce the size then you have to peel out the outer layers of black pixels further.
Think about training the network with your reference characters.
Remember that you have to feed back the output back to the input layer again and iterate it multiple times.
A while back I created a neural net to recognize digits 0-9 (python, sorry), so based on my (short) experience, 3 layers are ok and 96/50/3 topology will probably do a good job. As for the output layer, it's your choice; you can either backpropagate all 0s when the input image is not a D, O or M or use the fourth output neuron to indicate that the letter was not recognized. I think that the first option would be the best one because it's simpler (shorter training time, less problems debugging the net...), you just need to apply a threshold under which you classify the image as 'not recognized'.
I also used the sigmoid as activation function, I didn't try others but it worked :)
So I'm trying to do a pyramid in C# but I can't get it to print properly.
I'm doing this for my school's C# class, can't really figure out how to get the spaces in the pyramid properly. I feel like I'm really doing something wrong here.
Instead of a triangle I'm getting something like this:
*
**
***
****
*****
******
*******
********
Here is my code:
using System;
namespace Pyramidi
{
class Ohjelma
{
static void Main()
{
int korkeusMax = 0;
int valit = 0;
do
{
Console.Write("Anna korkeus: ");
korkeusMax = Convert.ToInt32(Console.ReadLine());
if (korkeusMax > 0) {
break;
}
else {
continue;
}
}
while(true);
for (int korkeus = 1; korkeus <= korkeusMax; korkeus++)
{
valit = (korkeusMax - korkeus) / 2;
for (int i = 0; i < valit; i++)
{
Console.Write(" ");
}
for (int leveys = 1; leveys <= korkeus; leveys++)
{
Console.Write("*");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
Try this:
for (int korkeus = 0; korkeus < korkeusMax; korkeus++)
{
for (int i = 0; i < (korkeusMax - korkeus - 1); i++)
{
Console.Write(" ");
}
for (int i = 0; i < (korkeus * 2 + 1); i++)
{
Console.Write("*");
}
Console.WriteLine();
}
Alternatively, instead of loops, you can use new String('*', num). Try this:
for (int korkeus = 0; korkeus < korkeusMax; korkeus++)
{
Console.Write(new String(' ', korkeusMax - korkeus - 1));
Console.Write(new String('*', korkeus * 2 + 1));
Console.WriteLine();
}
You are doing the first half right, but what you want to do for the second half is another for loop that does the opposite.
So you probably want to copy your for loop and change the header from
for (int korkeus = 1; korkeus <= korkeusMax; korkeus++)
to
for (int korkeus = kokeusMax; korkeus > 1; korkeus--)
or something along those lines
How to print a pattern using for loops?
Figure(3) Figure(4)
** **
** **
** **
** **
**
I tried this:
static void PrintPattern (int column)
{
for (int r = 0; r <= column + 1; r++)
{
Console.Write("**");
for (int c = 0; c < r; c++)
{
Console.WriteLine(" ");
}
Console.WriteLine();
}
}
made for fun, hope I won't receive too many -1s
int depth = 4;
var rows = Enumerable.Range(0, depth + 1)
.Select(v => new string('\t', v) + "**" );
var oneString = string.Join(Environment.NewLine, rows);
Console.WriteLine (oneString);
prints:
**
**
**
**
**
Remarks:
if you use ' ' as separator, instead of tab '\t', you'll get next result:
**
**
**
**
**
void Main()
{
const int rowCount = 10;
Console.Write("**");
for (var rowNumber = 0; rowNumber < rowCount - 1; rowNumber++)
{
Console.Write("\n ");
for (var spaceCount = 0; spaceCount < rowNumber; spaceCount++)
{
Console.Write(" ");
}
Console.Write("**");
}
}
Works just fine . . .
for figure3 : lines = 4, for figure4 : lines = 5
static void Main(string[] args)
{
int lines = 5;
for (int i = 0; i < lines; i++)
{
bool flag = false;
for (int j = 0; j < lines; j++)
{
if (j == i)
{
Console.WriteLine("**");
flag = true;
}
else
{
if (!flag)
Console.Write(" ");
}
}
}
}
I don't know C# but i'll help you in Java. You should change syntax as desired (Console.Write == System.out.print && Console.Writeline == System.out.println). So here goes the code:
static void printPattern(int column){
int spaceCount = 2;//number of spaces before **, change as needed
int k;//number of times ** is printed each row, must remain always 1
for(int i = 0; i < column; i++){
System.out.println();//starts each row with a new line
for(int j = 1; j < spaceCount; j++){
System.out.print(" ");//prints j spaces in each row
}
spaceCount++;//increment spacecount each row, so j can also go + 1
for(k = 1; k <= 1; k++){
System.out.print("**");//each row prints ** k times
}
k--;//k must remain 1
}
}
For Figure(3) call printPattern(4); for Figure(4) printPattern(5);
Hello everyone
I try to solve asterisk tree problem
and found my code is not work correctly and can be improved.
This is output that expected
input : 5
*
* * *
* * * * *
* * *
*
input : 4
* * * *
* *
* * * *
and this is my code
static void Main(string[] args)
{
Console.Write("input:");
char input = Console.ReadKey().KeyChar;
if (char.IsDigit(input))
{
int couter = (int)char.GetNumericValue(input);
Console.WriteLine();
if (couter % 2 != 0)
{
for (int i = 1; i <= couter; i++)
{
for (int j = 3; j > i; j--)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write(" *");
}
Console.WriteLine();
}
for (int i = couter - 1; i >= 3; i--)
{
for (int j = 1; j <= i; j++)
{
if (j <= couter - i)
{
Console.Write(" ");
}
else
{
Console.Write("* ");
}
}
Console.WriteLine();
}
}
else
{
for (int i = couter; i > 3; i--)
{
for (int j = 1; j <= i; j++)
{
if (couter - i >= j)
{
Console.Write(" ");
}
else
{
Console.Write("* ");
}
}
Console.WriteLine();
}
for (int i = couter - 1; i <= couter; i++)
{
for (int j = 0; j < i; j++)
{
Console.Write("* ");
}
Console.WriteLine();
}
}
}
}
Please could you help me to solve this problem.
Lately, I think I'm poor at algorithms and a little complex problem. Is anybody know useful link or how I can improve this skill, please let me know.
Thanks,
Check this page for input 5 (diamond) : http://www.dreamincode.net/forums/topic/126715-diamond-asterisk/
I've translated it to C# - now it displays diamonds with size that you set in variable 'rows':
int rows = 5;
StringBuilder sb = new StringBuilder();
// top part
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= rows - i; j++)
sb.Append(' ');
for (int k = 1; k <= 2 * i - 1; k++)
sb.Append('*');
sb.AppendLine();
}
//bottom part
for (int n = rows - 1; n > 0; n--)
{
for (int l = 1; l <= rows - n; l++)
sb.Append(' ');
for (int m = 1; m <= 2 * n - 1; m++)
sb.Append('*');
sb.AppendLine();
}
Console.Write(sb.ToString());
I was initially reluctant to post it because it definitely smells like homework...
Anyway, here's a piece of working code:
static void Main(string[] args)
{
Console.Write("input:");
char input = Console.ReadKey().KeyChar;
if (char.IsDigit(input))
{
int couter = (int)char.GetNumericValue(input);
Console.WriteLine();
if (couter % 2 != 0)
PrintDiamond(couter);
else
PrintHourGlass(couter);
}
Console.ReadLine();
}
private static void PrintDiamond(int couter)
{
bool moreAsterisks = true;
for (int row = 0; row < couter; row++)
{
int nAsterisks = moreAsterisks ? (2 * row) + 1 : 2 * (couter - row - 1) + 1;
int nSpaces = (couter - nAsterisks) / 2;
if (row == (couter - 1) / 2)
moreAsterisks = false;
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
for (int i = 0; i < nAsterisks; i++)
Console.Write("*");
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
Console.WriteLine();
}
}
private static void PrintHourGlass(int couter)
{
bool moreAsterisks = false;
for (int row = 0; row < couter - 1; row++)
{
int nAsterisks = moreAsterisks ? couter - 2 * (couter - row - 2) : couter - (2 * row);
int nSpaces = (couter - nAsterisks) / 2;
if (row == (couter - 2) / 2)
moreAsterisks = true;
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
for (int i = 0; i < nAsterisks; i++)
Console.Write("*");
for (int i = 0; i < nSpaces; i++)
Console.Write(" ");
Console.WriteLine();
}
}
P.S.:
it works with any number, not just 4-5...
Here's a minified LINQ solution for your problem:
class Program
{
static void Main(string[] args)
{
Console.Write("input: ");
string line = Console.ReadLine();
int n;
if (!int.TryParse(line, out n))
{
Console.WriteLine("Enter a valid integer number.");
return;
}
for (int i = 0; i < n; i++)
{
int l = Math.Abs(n - i * 2 - 1) + 1;
if (n % 2 != 0) l = n - l + 1;
Console.Write(Enumerable.Repeat(" ", n - l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
Console.WriteLine(Enumerable.Repeat("* ", l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
}
}
}
It's pretty simple; inside the loop, first line calculates length of the i-th diamond row if input is even, second one corrects the calculation for odd input. The remaining two lines print i-th row using some LINQ tricks. If you don't like showing off with LINQ, you can replace thoose lines with regular for loops (which is probably going to be faster). Then the code would look like:
class Program
{
static void Main(string[] args)
{
Console.Write("input: ");
string line = Console.ReadLine();
int n;
if (!int.TryParse(line, out n))
{
Console.WriteLine("Enter a valid integer number.");
return;
}
for (int i = 0; i < n; i++)
{
int l = Math.Abs(n - i * 2 - 1) + 1;
if (n % 2 != 0) l = n - l + 1;
//Console.Write(Enumerable.Repeat(" ", n - l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
//Console.WriteLine(Enumerable.Repeat("* ", l).DefaultIfEmpty("").Aggregate((a, b) => a + b));
for (int c = 0; c < n - l; c++) Console.Write(" ");
for (int c = 0; c < l; c++) Console.Write("* ");
Console.WriteLine();
}
}
}