[C#] Create Array on summing some variables

  • (2 Pages)
  • +
  • 1
  • 2

28 Replies - 6833 Views - Last Post: 30 April 2011 - 06:05 AM Rate Topic: -----

#16 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5572
  • View blog
  • Posts: 11,913
  • Joined: 02-June 10

Re: [C#] Create Array on summing some variables

Posted 25 April 2011 - 03:26 PM

Instructing you on how to design and archetect your entire application so that it works with the game emulator you are trying to hack interact with, how to design the logic to group all the items etc. is far beyond what we can cover in a simple thread.

"How do I design my application?" is simply far too broad of a question for this forum.
Was This Post Helpful? 0
  • +
  • -

#17 Ionut  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 385
  • View blog
  • Posts: 1,057
  • Joined: 17-July 10

Re: [C#] Create Array on summing some variables

Posted 25 April 2011 - 03:30 PM

Quote

Glad to see you've caught up with the conversation, Core.

I'm still way behind with this conversation,I keep reading the OP's situation and
I still see the problem like this: user enters 10, 20, 100, 100000 numbers(values = variables in OP's expression, but I ignored this aspect) and then you have to put this numbers in different arrays, the sum from every array being at most 100. And this is what does the code I posted.
Now looking over the second explanation, I am more confused, but I would let the OP think about how to get that code working for his project(because we should see some effort too and I hope to get 6 hours of full sleep this night)
Was This Post Helpful? 0
  • +
  • -

#18 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5572
  • View blog
  • Posts: 11,913
  • Joined: 02-June 10

Re: [C#] Create Array on summing some variables

Posted 25 April 2011 - 03:36 PM

View PostIonut, on 25 April 2011 - 04:30 PM, said:

(because we should see some effort too and I hope to get 6 hours of full sleep this night)


Luxury! I can only guess this is your weekend since you get to 'sleep in' like that. :sleep1:
Was This Post Helpful? 0
  • +
  • -

#19 Anthonidas  Icon User is offline

  • D.I.C Head

Reputation: 30
  • View blog
  • Posts: 218
  • Joined: 25-April 11

Re: [C#] Create Array on summing some variables

Posted 25 April 2011 - 03:44 PM

guys, i've edited my previous post...please have a look there.

again... i am not trying to hack anything!! theese items i'm talking about are stored in the database of the game BUT without groups! i have to create theese groups, if i want that the game works... do you understand?! i have full access to the database... i don't have to hack anything! i just have to create the groups... how should i explain that?! it's not difficult to understand, is it?

my application does not have to workwith the game. it just have to be a help in speeding up the work of distributing the items in different groups... now i'm doing it by hand, writing every single value in the database and calculating the percentage with a calculator (lol). but i would like to automatize it. i hope my intend is now clear...

anyway, i'll show you what i have already done, as soon as i am back on my computer. ;)

This post has been edited by Anthonidas: 25 April 2011 - 03:47 PM

Was This Post Helpful? 0
  • +
  • -

#20 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5572
  • View blog
  • Posts: 11,913
  • Joined: 02-June 10

Re: [C#] Create Array on summing some variables

Posted 25 April 2011 - 03:52 PM

Your desire is clear.

But your game archetecture is not.
Your actual situation in code is not.
We can't figure out if you are saying you have multiple individual variables like: var1, var2, var3
or if you already have an array of them: var[1], var[2], var[3]

You can yell "its in a database" all you want, but that doesn't tell us a thing about your utility code. Which as much as any of us can figure out by your description is badly designed.

But when you can provide us the code for your utility we will be able to understand more about what you are actually doing.
Was This Post Helpful? 0
  • +
  • -

#21 Core  Icon User is offline

  • using System.Linq;
  • member icon

Reputation: 774
  • View blog
  • Posts: 5,097
  • Joined: 08-December 08

Re: [C#] Create Array on summing some variables

Posted 25 April 2011 - 04:09 PM

Another attempt to understand the idea - so let's say you have a couple of objects - instances of a Unit class. This class has several properties and you want to group a batch of those together based on the sum of one of those properties. If that's the case, you can look what I posted before and apply the same idea, but with properties nested inside a class rather than variables - the main idea applies.
Was This Post Helpful? 1
  • +
  • -

#22 Anthonidas  Icon User is offline

  • D.I.C Head

Reputation: 30
  • View blog
  • Posts: 218
  • Joined: 25-April 11

Re: [C#] Create Array on summing some variables

Posted 26 April 2011 - 02:37 PM

hello again everybody :)

as promised i'll show you what i've done so far...

this is the final tool. you have the 3 text inputs, you have a button to save the file and you have one to open the saved file.
Posted Image

As i did not know how to make theese groups i've explained yesterday, i just coded the rest, without groups. that means, that when i press "Enter" or save my file, it simply adds the SQL-Line without changing the group.

This is my code:
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MySQL_Creator_C_Sharp
{
    public partial class MySQLCreator : Form
    {
        public static string Date = DateTime.Now.ToString("yyyyMMdd");
        public static string Time = DateTime.Now.ToString("HH:mm:ss");
        public static string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
        public static string SqlFile = Desktop + "\\" + Date + "_MySQL.sql";
        public static int group_id = 0;
        
        public MySQLCreator()
        {
            InitializeComponent();
        }

        private void MySQLCreator_Load(object sender, EventArgs e)
        {
            npc_txt.Focus();
        }

        private void CreateFile()
        {
            StreamWriter SW;



            try
            {
                if (File.Exists(SqlFile))
                {
                    byte[] array = new byte[30];

                    using (FileStream fs = new FileStream(SqlFile, FileMode.Open))
                    {
                        if (fs.CanSeek && fs.Length > 30)
                        {
                            fs.Position = fs.Length - 30;
                            fs.Read(array, 0, 30);
                        }
                    }

                    Encoding enc = new ASCIIEncoding();
                    string line = enc.GetString(array);
                    string[] npc_IDs = line.Split('(');
                    string[] npc_split = npc_IDs[1].Split(',');

                    //MessageBox.Show(npc_split[0]);

                    if (npc_split[0] != npc_txt.Text)
                    {
                        SW = File.AppendText(SqlFile);
                        SW.WriteLine("-- ---------------------------------------------------------------------------------------");
                        SW.Close();
                    }
                }

                SW = File.AppendText(SqlFile);
                SW.WriteLine("-- " + Time + " --");
                SW.WriteLine("REPLACE INTO `creature_loot_template` (`entry`, `item`, `ChanceOrQuestChance`, `groupid`) VALUES ({0}, {1}, {2}, {3});", npc_txt.Text, item_txt.Text, percent_txt.Text, group_id);
                SW.Close();
                item_txt.Text = "";
                percent_txt.Text = "";
                item_txt.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private bool IsNumeric(System.Object Expression)
        {
            if (Expression == null || Expression is DateTime)
                return false;

            if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
                return true;
            try
            {
                if (Expression is string)
                    Double.Parse(Expression as string);
                else
                    Double.Parse(Expression.ToString());
                return true;
            }
            catch { } // just dismiss errors but return false
            return false;
        }

        private void CheckExecute()
        {
            if (IsNumeric(npc_txt.Text) && IsNumeric(item_txt.Text) && IsNumeric(percent_txt.Text))
            {
                CreateFile();
            }
            else
            {
                if (IsNumeric(npc_txt.Text) == false)
                {
                    if (npc_txt.Text != "")
                    {
                        MessageBox.Show("Gli ID inseriti devono essere sempre in forma numerica", "Attenzione ID non valido!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    npc_txt.Focus();
                    npc_txt.SelectAll();
                }
                else if (IsNumeric(item_txt.Text) == false)
                {
                    if (item_txt.Text != "")
                    {
                        MessageBox.Show("Gli ID inseriti devono essere sempre in forma numerica", "Attenzione ID non valido!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    item_txt.Focus();
                    item_txt.SelectAll();
                }
                else
                {
                    if (percent_txt.Text != "")
                    {
                        MessageBox.Show("Gli ID inseriti devono essere sempre in forma numerica", "Attenzione ID non valido!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    percent_txt.Focus();
                    percent_txt.SelectAll();
                }
            }
        }

        private void create_btn_Click(object sender, EventArgs e)
        {
            CheckExecute();
        }

        private void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                CheckExecute();
        }

        private void open_btn_Click(object sender, EventArgs e)
        {
            //CreateFile();
            if (File.Exists(SqlFile))
            {
                System.Diagnostics.Process.Start(SqlFile);
            }
            else
            {
                MessageBox.Show("Il File \"" + Date + "_MySQL.sql\" non è ancora stato creato...", Date + "_MySQL.sql" + " non esiste!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}


Well, perhaps there are much better ways to do something like that... but as I said, I'm new to C# and this is my first program (except the standard "Hello World" ;) )
I also know, that i have to rewrite a big part of my code, to add this "groups calculation". but it doesn't matter as i find it's really interesting to understand why you have to do something or why you mustn't.

This post has been edited by Anthonidas: 26 April 2011 - 02:39 PM

Was This Post Helpful? 0
  • +
  • -

#23 Ionut  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 385
  • View blog
  • Posts: 1,057
  • Joined: 17-July 10

Re: [C#] Create Array on summing some variables

Posted 26 April 2011 - 02:58 PM

SW.WriteLine("REPLACE INTO `creature_loot_template` (`entry`, `item`, `ChanceOrQuestChance`, `groupid`) VALUES ({0}, {1}, {2}, {3});", npc_txt.Text, item_txt.Text, percent_txt.Text, group_id);


I think you meant
SW.WriteLine("INSERT INTO `creature_loot_template` (`entry`, `item`, `ChanceOrQuestChance`, `groupid`) VALUES ({0}, {1}, {2}, {3});", npc_txt.Text, item_txt.Text, percent_txt.Text, group_id);



I don't see where you keep the values from textboxes. I think you need to create a structure
struct ItemProperties
{ public int ItemId, MapId, Percentage; }


then create a List of ItemProperties and put the values from textboxes in here.
List<ItemProperties> userValue = new List<ItemProperties>();



About the algorithm, Core and I posted some code. Have you looked over it? Have you test it? Make a small console application and test those lines of code(you stated yesterday that Core undestood what you had to do, so maybe see if the code he provided would answer your question).
Was This Post Helpful? 1
  • +
  • -

#24 Anthonidas  Icon User is offline

  • D.I.C Head

Reputation: 30
  • View blog
  • Posts: 218
  • Joined: 25-April 11

Re: [C#] Create Array on summing some variables

Posted 26 April 2011 - 03:31 PM

ehm no, i have to use "replace" because some items exists already in my DB and have to be updated, other ones don't so they have to be created.

yep i have looked over them but not tested yet. in fact core understood what i was trying to do, but i was not that sure in how to store the inserted values. what you told me to do sounds really good:

View PostIonut, on 26 April 2011 - 02:58 PM, said:

I don't see where you keep the values from textboxes. I think you need to create a structure
struct ItemProperties
{ public int ItemId, MapId, Percentage; }


then create a List of ItemProperties and put the values from textboxes in here.
List<ItemProperties> userValue = new List<ItemProperties>();



I'm going to googleing for Lists in C# now, because I don't know how they work. (I must admit that I did even not know, that they exist. lol) Thank you for the hints. This gives some + for you three guys. ;)
Was This Post Helpful? 0
  • +
  • -

#25 Ionut  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 385
  • View blog
  • Posts: 1,057
  • Joined: 17-July 10

Re: [C#] Create Array on summing some variables

Posted 27 April 2011 - 01:31 AM

MSSql, MySql,Oracle all are relational databases that use SQL(structured query language). One property of this language is that you can perform 4 standard operation on the data: select, insert, update, delete(all are self explanatory). Replace is used for string manipulation(this in MSSQL, I don't know about the rest). To change data from a table, use update.
Was This Post Helpful? 0
  • +
  • -

#26 Anthonidas  Icon User is offline

  • D.I.C Head

Reputation: 30
  • View blog
  • Posts: 218
  • Joined: 25-April 11

Re: [C#] Create Array on summing some variables

Posted 27 April 2011 - 01:57 AM

View PostIonut, on 27 April 2011 - 01:31 AM, said:

MSSql, MySql,Oracle all are relational databases that use SQL(structured query language). One property of this language is that you can perform 4 standard operation on the data: select, insert, update, delete(all are self explanatory). Replace is used for string manipulation(this in MSSQL, I don't know about the rest). To change data from a table, use update.


There is no difference between Replace and Insert or Update, except that it is slower... I know MySQL, and that's also not the point. The advantage of using REPLACE is that: "REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted." And this is exactly what I need, because there will be items they don't exist in my DB and other ones they do. But at the time I use my tool, I do not know which ones exist and which ones don't. That's why I use "REPLACE" and a check for existance would just take too loong time.

Anyway I have read this article on Lists in C# (C# List and ArrayList Collections) and I am a bit confused... what is the difference between lists and normal arrays? I did not understand this point.


EDIT:
Ok I have found the following explanation:

Quote

ArrayList stores everything as an object, and when you retrieve the value you have to cast it back into the actual object type if you want to use any of the objects methods, etc.

List<T> is a generic container type that you specify what type it can hold when you instantiate the List<T>. You don't have to cast the object back into the type.


but what is the difference between List<T> AND a normal/simple array? Can Lists also be multidimensional?

This post has been edited by Anthonidas: 27 April 2011 - 02:02 AM

Was This Post Helpful? 0
  • +
  • -

#27 Anthonidas  Icon User is offline

  • D.I.C Head

Reputation: 30
  • View blog
  • Posts: 218
  • Joined: 25-April 11

Re: [C#] Create Array on summing some variables

Posted 27 April 2011 - 02:18 AM

Is this explanation right? I have found different articles saying this is not accurate...

Quote

List<string> is class with a private member that is a string[]. The MSDN documentation states this fact in several places. The List class is basically a wrapper class around an array that gives the array other functionality.

....... bla bla bla .........

If you intend on having a data structure that grows over time (gets more and more elements), performance (ave. speed) wise the List will start to shine. That is because each time you resize an array to add another element it is an O(n) operation. When you add an element to a List (and the list is already at capacity) the list will double itself in size. I won't get into the nitty gritty details, but basically this means that increasing the size of a List is on average a O(log n) operation. Of course this has drawbacks too (you could have almost twice the amount of memory allocated as you really need if you only go a couple items past its last capacity).

Was This Post Helpful? 0
  • +
  • -

#28 Core  Icon User is offline

  • using System.Linq;
  • member icon

Reputation: 774
  • View blog
  • Posts: 5,097
  • Joined: 08-December 08

Re: [C#] Create Array on summing some variables

Posted 27 April 2011 - 08:33 PM

Somewhat accurate. List<string> != string[]. Generally, working directly with arrays might reduce a possible performance overhead, but for convenience purposes, using generic collections (aka List<T>, Dictionary<T> etc.) is acceptable.

List<T> implements IEnumerable that lets you enumerate the data in different ways (e.g. access it via LINQ). It is a collection of an undefined size (unlike an array) on the user's side. Internally, it works with an array and declares the initial capacity to 4, but it behaves a bit differently. I would highly recommend looking at it via Reflector - it shows you how it works internally.
Was This Post Helpful? 1
  • +
  • -

#29 Anthonidas  Icon User is offline

  • D.I.C Head

Reputation: 30
  • View blog
  • Posts: 218
  • Joined: 25-April 11

Re: [C#] Create Array on summing some variables

Posted 30 April 2011 - 06:05 AM

Hey Guys, my tool works :)

I must admit, that it was not as difficult as I thought before but I am sure that perhaps there are better ways to do things like that. Have a look at my final code... Are there some parts I could rewrite in an easyer way? Or perhaps do changes that improove performance? (Ok at the moment my tool doesn't have to handle much data, but supposed it would be a bigger load of data, would my tool be stable??)

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MySQL_Creator_C_Sharp
{
    public partial class MySQLCreator : Form
    {
        //public static string Date = DateTime.Now.ToString("yyyyMMdd");
        //public static string Time = DateTime.Now.ToString("HH:mm:ss");
        public static string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
        public static string SqlFile = Desktop + "\\" + DateTime.Now.ToString("yyyyMMdd") + "_MySQL.sql";

        public static int lastNPCId;
        public List<string> insertedItems = new List<string>();  // string composta da: "npcID|itemID|percent|groupID"

        public MySQLCreator()
        {
            InitializeComponent();
            this.Closing += new System.ComponentModel.CancelEventHandler(this.MySQLCreator_Closing);
        }

        private void MySQLCreator_Load(object sender, EventArgs e)
        {
            npc_txt.Focus();
        }


        void MySQLCreator_Closing(object sender, CancelEventArgs e)
        {
            if (MessageBox.Show("Vuoi salvare lo script prima di chiudere?", "Salva File", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                CreateFile(0);
            }
        }

        private bool IsNumeric(System.Object Expression)
        {
            if (Expression == null || Expression is DateTime)
                return false;

            if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
                return true;
            try
            {
                if (Expression is string)
                    Double.Parse(Expression as string);
                else
                    Double.Parse(Expression.ToString());
                return true;
            }
            catch { }
            return false;
        }

        private void CheckExecute()
        {
            if (IsNumeric(npc_txt.Text) && IsNumeric(item_txt.Text) && IsNumeric(percent_txt.Text))
            {
                if (insertedItems.Count >= 1 && lastNPCId != 0)
                {
                    if (lastNPCId != 0 && lastNPCId != int.Parse(npc_txt.Text))
                    {
                        CreateFile(int.Parse(npc_txt.Text));
                    }
                    else
                    {
                        CreateGroupsAndInsertList();
                    }
                }
                else
                {
                    CreateGroupsAndInsertList();
                }
            }
            else
            {
                if (IsNumeric(npc_txt.Text) == false)
                {
                    if (npc_txt.Text != "")
                    {
                        MessageBox.Show("Gli ID inseriti devono essere sempre in forma numerica", "Attenzione ID non valido!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    npc_txt.Focus();
                    npc_txt.SelectAll();
                }
                else if (IsNumeric(item_txt.Text) == false)
                {
                    if (item_txt.Text != "")
                    {
                        MessageBox.Show("Gli ID inseriti devono essere sempre in forma numerica", "Attenzione ID non valido!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    item_txt.Focus();
                    item_txt.SelectAll();
                }
                else
                {
                    if (percent_txt.Text != "")
                    {
                        MessageBox.Show("Gli ID inseriti devono essere sempre in forma numerica", "Attenzione ID non valido!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    percent_txt.Focus();
                    percent_txt.SelectAll();
                }
            }
        }

        private void CreateGroupsAndInsertList()
        {
            int groupID = 0;
            int percentNew = int.Parse(percent_txt.Text);

            if (percentNew <= 0)
            {
                groupID = 0;
            }
            else
            {
                if (insertedItems.Count == 0)
                {
                    groupID = 1;
                }
                else
                {
                    for (int x = 1; x < 10; x++)
                    {
                        int current_total = 0;

                        foreach (string ArrValue in insertedItems)
                        {
                            string[] elements = ArrValue.Split('|');
                            int npcID = int.Parse(elements[0]);
                            int itemID = int.Parse(elements[1]);
                            int perc = int.Parse(elements[2]);
                            int group = int.Parse(elements[3]);

                            if (group == x)
                            {
                                current_total += perc;
                            }
                        }

                        if ((current_total + percentNew) <= 100)
                        {
                            groupID = x;
                            break;
                        }
                    }
                }
            }
            insertedItems.Add(npc_txt.Text + "|" + item_txt.Text + "|" + percentNew + "|" + groupID);
            lastNPCId = int.Parse(npc_txt.Text);
            item_txt.Text = "";
            percent_txt.Text = "";
            item_txt.Focus();
        }

        private void CreateFile(int npcID)
        {
            if (npc_txt.Text != "" && item_txt.Text != "" && percent_txt.Text != "" && npcID == 0)
            {
                CheckExecute();
            }

            StreamWriter SW;
            try
            {
                if (insertedItems.Count <= 0)
                {
                    MessageBox.Show("Non ho niente da scrivere!", "Dati non disponibili...", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    SW = File.AppendText(SqlFile);
                    SW.WriteLine("-- " + DateTime.Now.ToString("HH:mm:ss") + " --");
                    SW.WriteLine("REPLACE INTO `creature_loot_template` (`entry`, `item`, `ChanceOrQuestChance`, `groupid`) VALUES");

                    for (int i = 0; i < insertedItems.Count; i++)
                    {
                        string[] elements = insertedItems[i].Split('|');
                        int WnpcID = int.Parse(elements[0]);
                        int WitemID = int.Parse(elements[1]);
                        int Wperc = int.Parse(elements[2]);
                        int Wgroup = int.Parse(elements[3]);

                        if (i == insertedItems.Count - 1)
                        {
                            SW.WriteLine("({0}, {1}, {2}, {3});", WnpcID, WitemID, Wperc, Wgroup);
                        }
                        else
                        {
                            SW.WriteLine("({0}, {1}, {2}, {3}),", WnpcID, WitemID, Wperc, Wgroup);
                        }
                    }
                    insertedItems.Clear();
                    SW.Close();

                    if (npc_txt.Text != "" && item_txt.Text != "" && percent_txt.Text != "" && npcID != 0)
                    {
                        CheckExecute();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void create_btn_Click(object sender, EventArgs e)
        {
            CreateFile(0);
        }

        private void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                CheckExecute();
        }

        private void open_btn_Click(object sender, EventArgs e)
        {
            if (File.Exists(SqlFile))
            {
                System.Diagnostics.Process.Start(SqlFile);
            }
            else
            {
                MessageBox.Show("Impossibile aprire il File \"" + DateTime.Now.ToString("yyyyMMdd") + "_MySQL.sql\". Non  ancora stato creato.", DateTime.Now.ToString("yyyyMMdd") + "_MySQL.sql" + " non esiste!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}


Thanks again for your help :)
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2