Skip to content

Instantly share code, notes, and snippets.

@Measter
Created March 14, 2014 06:18
Show Gist options
  • Save Measter/9542916 to your computer and use it in GitHub Desktop.
Save Measter/9542916 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
namespace ConsoleTestApp
{
public class Pyramid
{
private const int PRIME_COLOUR_R = 0x00, PRIME_COLOUR_G = 0x00, PRIME_COLOUR_B = 0x00;
private const int N_PRIME_COLOUR_R = 0xC3, N_PRIME_COLOUR_G = 0xC3, N_PRIME_COLOUR_B = 0xC3;
private const int SPACING = 1;
private const int SQUARE_SIZE = 2;
private const int MARGIN = 5;
public static void Generate( int height, string filename )
{
int rowSize = 1;
int itemCount = 0;
List<List<bool>> data = new List<List<bool>>();
List<bool> curRow = new List<bool>();
for( int i = 0; i < height * height; i++ )
{
itemCount++;
curRow.Add( IsPrime( i ) );
if( rowSize == itemCount )
{
data.Add( curRow );
curRow = new List<bool>();
rowSize += 2;
itemCount = 0;
}
}
SaveImage( data, filename );
}
private static bool IsPrime( int n )
{
if( n < 2 )
return false;
if ( n == 2 || n == 3 || n == 5 )
return true;
if( n % 2 == 0 || n % 3 == 0 || n % 5 == 0 )
return false;
int m = (int)Math.Sqrt( n );
for( int i = 7; i < m; i += 2 )
{
if( n % i == 0 )
return false;
}
return true;
}
private static void SaveImage( List<List<bool>> data, string filename )
{
if( data.Count == 0 )
throw new Exception( "Data is empty." );
int height = ( data.Count * SQUARE_SIZE ) + ( data.Count - 1 ) * SPACING;
int width = ( data.Last().Count * SQUARE_SIZE ) + ( data.Last().Count - 1 ) * SPACING;
if( data.Last().Count % 2 == 0 )
width += ( SQUARE_SIZE + SPACING );
height += MARGIN * 2;
width += MARGIN * 2;
Bitmap bmp = new Bitmap( width, height, PixelFormat.Format24bppRgb );
Graphics g = Graphics.FromImage( bmp );
List<bool> curRow;
SolidBrush primeBrush = new SolidBrush( Color.FromArgb( PRIME_COLOUR_R, PRIME_COLOUR_G, PRIME_COLOUR_B ) );
SolidBrush nPrimeBrush = new SolidBrush( Color.FromArgb( N_PRIME_COLOUR_R, N_PRIME_COLOUR_G, N_PRIME_COLOUR_B ) );
int dataWidth = data.Last().Count;
g.Clear( Color.White );
for( int y = 0; y < data.Count; y++ )
{
curRow = data[y];
int startX = ( dataWidth / 2 ) - ( curRow.Count / 2 );
for( int x = startX, i = 0; i < curRow.Count; x++, i++ )
{
g.FillRectangle( curRow[i] ? primeBrush : nPrimeBrush, GetRectangle( x, y ) );
}
}
g.Dispose();
bmp.Save( filename );
bmp.Dispose();
}
private static Rectangle GetRectangle( int x, int y )
{
int newY = ( y * SQUARE_SIZE ) + ( y - 1 ) * SPACING + MARGIN;
int newX = ( x * SQUARE_SIZE ) + ( x - 1 ) * SPACING + MARGIN;
return new Rectangle( newX, newY, SQUARE_SIZE, SQUARE_SIZE );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment