|
Hi everyone, I'm supposed to make a program that finds all the magic squares of size 6, but there are 36! possible combinations of squares to check, so my programs runs forever, perhaps with a million servers I could actually find a solution, so here is my question: Anyone knows a way of running my C# application in multiple computers at the same time?
Here is my code, perhaps anyone can improve it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using System.Threading;
namespace MagicSquare
{
public partial class Form1 : Form
{
Thread bgWorker = null;
public Form1()
{
InitializeComponent();
}
struct StateInfo
{
public int Size { get; set; }
public bool PanMagic { get; set; }
}
private void threadMethod(object state)
{
MagicSquare msq = new MagicSquare(((StateInfo)state).Size, ((StateInfo)state).PanMagic);
msq.FindEnd += new EventHandler(msq_FindEnd);
msq.FindStart += new EventHandler(msq_FindStart);
msq.MagicSquareFound += new MagicSquare.MagicSquareEventHandler(msq_MagicSquareFound);
msq.FindMagicSquares();
}
void msq_MagicSquareFound(object sender, MagicSquare.MagicSquareEventArgs e)
{
StringBuilder temp = new StringBuilder(textBox1.Text);
temp.Append("---START---\r\n");
for (int i = 0; i < e.Matrix.GetLength(0); i++)
{
for (int j = 0; j < e.Matrix.GetLength(1); j++)
temp.Append(string.Format("{0}{1}", e.Matrix[j, i], j + 1 == e.Matrix.GetLength(0) ? string.Empty : ", "));
temp.Append("\r\n");
}
temp.Append("---END---\r\n");
textBox1.Invoke(new ParameterizedThreadStart(delegate(object state)
{
textBox1.Text = (string)state;
}), temp.ToString());
}
void msq_FindStart(object sender, EventArgs e)
{
working = true;
textBox1.Invoke(new ParameterizedThreadStart(delegate(object state)
{
textBox1.Text = (string)state;
}), string.Empty);
}
void msq_FindEnd(object sender, EventArgs e)
{
working = false;
button1.Invoke(new ParameterizedThreadStart(delegate(object state)
{
button1.Text = (string)state;
}), "Start");
progressBar1.Invoke(new ThreadStart(delegate()
{
progressBar1.Visible = false;
}));
}
private bool working = false;
private void button1_Click(object sender, EventArgs e)
{
if (working) //lo tumbo
{
bgWorker.Abort();
((Control)sender).Text = "Start";
progressBar1.Visible = false;
}
else//lo prendo
{
((Control)sender).Text = "Stop";
progressBar1.Visible = true;
bgWorker = new Thread(threadMethod);
bgWorker.Start(new StateInfo { Size = Convert.ToInt32(numericUpDown1.Value), PanMagic=checkBox1.Checked});
}
working = !working;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
class MagicSquare
{
public class MagicSquareEventArgs : EventArgs
{
public int[,] Matrix { get; set; }
}
public delegate void MagicSquareEventHandler(object sender, MagicSquareEventArgs e);
public event EventHandler FindStart;
public event EventHandler FindEnd;
public event MagicSquareEventHandler MagicSquareFound;
public bool PanMagic { get; private set; }
public int Size { get; private set; }
public const int BOTTOM = 1;
public readonly int TOP;
public int N
{
get
{
return Size * ((Size * Size) + 1) / 2;
}
}
public MagicSquare(int _size, bool _panMagic)
{
Size = _size;
TOP = Size * Size;
PanMagic = _panMagic;
}
private bool isPerfectSquareLine(int number)
{
//double sqrt = Math.Sqrt(number);
//return sqrt == (int)sqrt;
return N == number;
}
private bool isMagicSquare(int[,] square)
{
int MATRIX_SIZE = square.GetLength(0);
int tempSum = 0;
#region |
for (int i = 0; i < MATRIX_SIZE; i++)
{
tempSum = 0;
for (int j = 0; j < MATRIX_SIZE; j++)
tempSum += square[i, j];
if (!isPerfectSquareLine(tempSum))
return false;
}
#endregion
#region -
for (int i = 0; i < MATRIX_SIZE; i++)
{
tempSum = 0;
for (int j = 0; j < MATRIX_SIZE; j++)
tempSum += square[j, i];
if (!isPerfectSquareLine(tempSum))
return false;
}
#endregion
if (PanMagic)
{
#region \
tempSum = 0;
for (int i = 0; i < MATRIX_SIZE; i++)
tempSum += square[i, i];
if (!isPerfectSquareLine(tempSum))
return false;
#endregion
#region /
tempSum = 0;
for (int i = 0; i < MATRIX_SIZE; i++)
tempSum += square[i, MATRIX_SIZE - 1 - i];
if (!isPerfectSquareLine(tempSum))
return false;
#endregion
}
return true;
}
private int[,] blankMatrix()
{
int[,] result = new int[Size, Size];
for (int i = 0; i < Size; i++)
for (int j = 0; j < Size; j++)
result[i, j] = BOTTOM - 1;
return result;
}
private int[,] cloneMatrix(int[,] matrix)
{
int[,] result = new int[matrix.GetLength(0), matrix.GetLength(1)];
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++)
result[i, j] = matrix[i, j];
return result;
}
private bool containsNumber(int n, int[,] matrix)
{
foreach (int i in matrix)
if (i == n) return true;
return false;
}
private bool isFull(int[,] matrix)
{
foreach (int i in matrix)
if (i < BOTTOM) return false;
return true;
}
private List<int[,]> result = null;
private int[,] matrix = null;
public void FindMagicSquares()
{
if (FindStart != null)
FindStart.Invoke(this, new EventArgs());
result = new List<int[,]>();
matrix = blankMatrix();
for (int i = 0; i < Size; i++)
for (int j = 0; j < Size; j++)
findMagicSquares(BOTTOM, i, j);
matrix = null;
if (FindEnd != null)
FindEnd.Invoke(this, new EventArgs());
}
private void findMagicSquares(int n, int i, int j)
{
matrix[i, j] = n++;
if (isFull(matrix))
{
if (isMagicSquare(matrix))
{
result.Add(cloneMatrix(matrix));
if (MagicSquareFound != null)
MagicSquareFound.Invoke(this, new MagicSquareEventArgs { Matrix = result.Last() });
}
}
else
{
if (!containsNumber(n, matrix))
{
for (int _i = 0; _i < Size; _i++)
for (int _j = 0; _j < Size; _j++)
if (matrix[_i, _j] < BOTTOM)
findMagicSquares(n, _i, _j);
}
}
matrix[i, j] = BOTTOM - 1;
}
public List<int[,]> Result { get { return result; } }
}
}
|
|
|
|
|
You calculate the sums of all rows, columns and diagonals to check if a given array is a magic square, right?
You don't have to do it - you can:
(1) stop the calculations right after you get two different sums (two sums at minimum are needed to determine that a given array is not a magic square),
(2) or even better, use the formula SUM = n*(n^2+1)/2 and calculate the sums only to the point when you get one that does not equal SUM (even one sum may prove that a given array is not a magic square).
This should speed up things, although I don't know if this will be enough.
Please use the code block tags when pasting code into your message. And consider pasting only the important pieces.
|
|
|
|
|
hey man thanks for your answer. but I do check for n*(n^2+1)/2, this is the N property of my class, and the method isMagicSquare returns false if there is a single row or column wich sum is different from N. I made a multithreaded approach in a newer to solve the problem, but it still takes too long. but thanks anyway and sorry for the long code. I thought it will be smaller
|
|
|
|
|
Camilo Sánchez Herrera wrote: this is the N property of my class, and the method isMagicSquare returns false if there is a single row or column wich sum is different from N
Sorry, I didn't notice that.
I cannot understand how you generate the squares to check, but, if you're not already doing it, maybe you could check every generated row and only generate a next one if the sum of the previous one equals N.
BTW, is it a school/university assignment?
|
|
|
|
|
Hello Guyes,
i have built a web application in VS20005 using C#. Its an eCommerce application. I want to implement UPS for shipment method to calculate the rates and all other thing related to shipment. But I don’t find any information that how I can implement UPS in my site. Is there any one who can help me. There is also no document on UPS.com from where I can extract the way of implementation, please provide some sample code which can help me to integrate UPS on my site.
|
|
|
|
|
I think you need to contact UPS directly. I would expect you need a UPS account to be able to calculate rates etc as rates are probably customer dependant.
Bob
Ashfield Consultants Ltd
|
|
|
|
|
<pre>--------------------------------------------------------------------------------
I wrote code to access structre from C# .net where structure is in C dll .here are the two files .when i debug the code i got runtime exception i.e MarshalDirectiveException saying that Cannot marshal 'return value': Pointers cannot reference marshaled structures. Use ByRef instead.
------------------------- StrcutreDisplay.dll---------------------------------
#include<iostream.h>
#include<conio.h>
#include<malloc.h>
#include<string.h>
extern "C"
{
typedef struct
{
char *fname;
char *lname;
char abc[5];
}Detail;
__declspec(dllexport) Detail * Disp()
{
Detail *ptr=(Detail *)malloc(sizeof(Detail));
ptr->fname = (char*)malloc(50);
memset(ptr->fname, 0x00, 50);
ptr->lname = (char*)malloc(50);
memset(ptr->lname, 0x00, 50);
memset(ptr->abc, 0x00, 5);
strcpy(ptr->fname, "larson");
strcpy(ptr->lname, "scolari");
strcpy(ptr->abc, "ABC");
return ptr;
}
}
----------------------------StructureExample---------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace StructureExample
{
class Program
{
[StructLayout(LayoutKind.Explicit)]
public struct Detail
{ // [MarshalAs(UnmanagedType.LPStr)]
public unsafe sbyte* fname;
public unsafe sbyte* lname;
[MarshalAs (UnmanagedType.ByValArray,SizeConst=5)]
public unsafe fixed char abc[5];
}
// strucure DLL
[DllImport("StructureDisplay.dll")]
public static unsafe extern Detail * Disp();
static void Main(string[] args)
{
unsafe
{
Detail * var = Disp();//Cannot marshal 'return value': Pointers cannot reference marshaled structures. Use ByRef instead.
string a = new string(var->fname);
string b = new string(var->lname);
string e = new string(var->abc);
}
Console.WriteLine("hello world");
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(e);
Console.Read();
}
}
}
------------------------------------------------------------------------------------------------
Can anyone help me out to solve this problem?what i need to do to solve this problem?
Any help appreciated.
Thanks in advance.</pre>
|
|
|
|
|
I dont know the answer you are looking for. Maybe something like the following will work better:
void Disp(out Detail d);
I am not sure what you are trying to do either. If you had any experience in C/C++ you would know not to blindly return allocated memory. Where do you free this memory?
|
|
|
|
|
i want to connect network pc through IP address. how it is possible. i am using namespace.
System.Net.Sockets;
System.Net
|
|
|
|
|
Duplicate Post . Please Ignore
|
|
|
|
|
i am trying to write a method that checks whether an object can be cast to a specific type:
that is, something like this:
bool CheckConfigVariable(object variable, Type expectedType) {
if (variable is expectedType) {
return true;
}
return false;
}
but that doesn't seem to work. I've also tried:
object hello;
hello = (object)variable;
if (typeof(hello) == Type.GetTypeCode(typething)) {
return true;
}
return false;
}
which sort of works, but it can't find the hello variable in the typeof function. How would I go about checking whether the object is a certain type from what is provided in the parameters of the called method?
Mike
|
|
|
|
|
Please try with the code given below.
bool CheckConfigVariable(object variable, Type expectedType)
{
if (variable.GetType() == expectedType)
{
return true;
}
return false;
}
Software - Bundle of bugs covered with features.
|
|
|
|
|
typeof takes the type, I thought, as in typeof(int). I think you need hello.GetType()
Christian Graus
Please read this if you don't understand the answer I've given you
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
This isn't exactly doing what i thought it was doing sorry.
variable.GetType() == expectedType is checking whether Object is equal to Type blah.
Its always returning false. I just want it to return if it is compatible with casting it to another object, not if it is the same type.
|
|
|
|
|
OK, perhaps generics will help. Because what you need is access to the type to call 'is' as you were trying to do. Passing a Type doesn't sound like it worked, but if the type is specified and your generic method says something like
return (myvar is T);
Christian Graus
Please read this if you don't understand the answer I've given you
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
Christian Graus wrote: return (myvar is T);
where T is my parameter of type?
bool CheckConfigVariable(object variable, Type expectedType) {
return (variable is expectedType);
}
i get the error: The type or namespace name 'expectedType' could not be found (are you missing a using directive or an assembly reference?) (CS0246)
|
|
|
|
|
Yeah, but you write a generic method instead.
static bool CheckType<T>(object o)
{
return (o is T);
}
Then you call it like this:
DateTime dt = DateTime.Now;
bool b = CheckType<int>(dt);
Christian Graus
Please read this if you don't understand the answer I've given you
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
wow, I didn't know how that worked. Now I'll have to go and do some more indepth reading on Generics.
Just another question on comparing types. How do enums fit into the picture? Is enum a type?
Can I compare a string to an enum (using the method above (using is keyword)), or one of the values in the enumto see if it can be converted?
|
|
|
|
|
You use Enum.Parse to convert a string to an enum. An enum is a type.
Christian Graus
Please read this if you don't understand the answer I've given you
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
Thank you so much for your help, it is greatly appreciated.
|
|
|
|
|
Glad to help
Christian Graus
Please read this if you don't understand the answer I've given you
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
|
private static bool
F
(
object o
,
System.Type t
)
{
if ( o == null )
{
throw ( new System.ArgumentNullException() ) ;
}
return ( t.IsAssignableFrom ( o.GetType() ) ) ;
}
And may I humbly suggest my TypeTransmogrifier[^] ?
|
|
|
|
|
protected void bn_delete_Click(object sender, EventArgs e)
{
bn_del.Attributes("onclick") = "return confirm('Are you sure you wish to delete these records?');";
GridViewRow row;
foreach (row in GridView1.Rows) {
CheckBox idcb = row.FindControl("CheckBox1");
TextBox id = row.FindControl("id");
if (idcb.Checked) {
DataAccessLayer dal = new DataAccessLayer();
dal.Connect();
dal.deleteDB("DELETE FROM StaffID Where StaffIDID = '" + id.Text + "'");
dal.Close();
getStaff();
}
error message: type and identifier are both required in a foreach
statement
|
|
|
|
|
twistz wrote: foreach (row in GridView1.Rows)
I think you need to do
foreach (GridViewRow row in GridView1.Rows)
Christian Graus
Please read this if you don't understand the answer I've given you
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|