Programming

Counting Size of Struct in C

First, i didn’t guarantee that this post will give a true answer for any problem because this conclusion just made by myself based on my observation on some codes. It’s very welcome to give another opinions or answers to share more knowledge and better solution.

This post will discuss about how much a struct take a memory? because of structs is a user-defined data structures, it’s size will be relative to the content that the struct stores. For beginning let’s refresh our memory (brain) about two most-used primitive data types size.

  1. int (4 bytes / 32 bits)
  2. char (1 bytes / 8 bits)

Read More →

Simple HTTP Proxy Server C# Source Code

This time my next step for building the M-NIC Projects, creating a HTTP Proxy Server which is actually just an HTTP Relay :D. The concept just take everything from applications which HTTP Proxy server is set to my application then relaying the request to the destination server then relay again the response from destination server to client application.

The method? Just ordinary Socket Programming in C# (System.Net) Socket.Send(), Socket.Receive(), etc. First let’s take a look to the Server Listener, every server must listen to the incoming client connection. In this application, i’m using TcpListener for that.

using System.Net;
using System.Net.Sockets;

namespace SimpleHttpProxy
{
    class ServerListerner
    {
        private int listenPort;
        private TcpListener listener;

        public ServerListerner(int port)
        {
            this.listenPort = port;
            this.listener = new TcpListener(IPAddress.Any, this.listenPort);
        }

        public void StartServer()
        {
            this.listener.Start();
        }

        public void AcceptConnection()
        {
            Socket newClient = this.listener.AcceptSocket();
            ClientConnection client = new ClientConnection(newClient);
            client.StartHandling();
        }

    }
}

How it works? See the main method implementation below. Just initiate server listener object which is listen to port 9000 (this port number is up to you, but make sure you’re choosing free port number), then start the server to make the server ready to accept incoming connection and do the magic loop (actually just an infinite looping) to accept the incoming connection.

Read More →

Hello World MPI C Source Code

Got something interesting, MPI (Message Passing Interface) is the language or library which needed to create parallel programming. So let’s start with the usual way to begin code, “Hello World”. This post will be show how to make the simplest MPI code in C language.

#include "stdio.h"
#include "mpi.h"
 
int main(int argc, char** argv)
{
    int rank;
    int size;
 
    /* Initialize MPI  */
    MPI_Init(&argc, &argv);
 
    /* Getting the World Size and Process Number (rank) */
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
 
    /* Routine for process 0 */
    if (rank == 0)
    {
        printf("P%d : I Found this world size is %d processesn", rank, size);
        printf("P%d : Hello World! This is process number %d writing!n", rank, rank);
    }
    /* Routine for process 1 */
    else if (rank == 1)
    {
        printf("P%d : I Found this world size is %d processesn", rank, size);
        printf("P%d : Hello World! This is process number %d writing!n", rank, rank);
    }
    /* Routine for Other Processes */
    else
    {
        printf("P%d : I'm Unused Process...n", rank);
    }
 
    /* End of MPI */
    MPI_Finalize();
    return 0;
}

Read More →

Branch and Bound Unbounded Knapsack Java Source Code

Branch and Bound, this is the another way to solve unbounded knapsack problem beside Dynamic Programming Solving like the previous post [Dynamic Programming Unbounded Knapsack]. This way is called Branch and Bound, i’m still confusing with the concepts of this algorithm and how can it solve the problem with optimal result. But for now just forget it and focus on implementating with Java Programming Language.

This algorithm consist of 4 (four) main parts.

  1. Pre Processing :: Sort the items with ascending order by it’s ratio (value/weight)
  2. Initializing :: Take a Greedy Choosing for item 1, then 2, and so on
  3. Reduction Move :: Decrement the least significant digit (most right non-zero)
  4. Expansion Move :: Take a Greedy Choosing for items on right of least significant digit

If you’re still confuse about my explaination, please go to my reference site [BB Unbounded Knapsack]

Okay let’s go to the implementing with source code. First of course declaring the variable…

    private static int   maxWeight = 0; //maximum weight of knapsack
    private static int[] w;             //weight of each item
    private static int[] v;             //value of each item
    private static int[] maxSet;        //set of optimum items
    private static int   maxValue;      //value of maximum set

Then we make the user input getter

    private static boolean getData()
    {
        System.out.print("Input Maximum Knapsack Weight : ");
            maxWeight = new Scanner(System.in).nextInt();

        System.out.print("Input the weight of each item (separate by space) : ");
            String[] temp = new Scanner(System.in).nextLine().split(" ");
            w = new int[temp.length];
            for (int i=0;i<temp.length;i++) w[i] = Integer.valueOf(temp[i]);

        System.out.print("Input the value of each item (separate by space) : ");
            temp = new Scanner(System.in).nextLine().split(" ");
            v = new int[temp.length];
            for (int i=0;i<temp.length;i++) v[i] = Integer.valueOf(temp[i]);

        if (w.length != v.length){
            System.err.println("Number of weight and value data not match!");
            return false;
        }
        return true;
    }

Now, the first step of this algorithm. Pre-Processing

    private static void preProcessing()
    {
        /**
         * Sorting using Selection Sort to Arrange
         * the data by it's ratio (value/weight)
         */
        for (int i=0;i<w.length-1;i++)
        {
            int minIndex = i;
            for (int j=i+1;j<w.length;j++)
            {
                if ((double)v[j]/w[j] < (double)v[minIndex]/w[minIndex])
                {
                    minIndex = j;
                }

            }
            int temp    = w[i];
            w[i]        = w[minIndex];
            w[minIndex] = temp;

            temp        = v[i];
            v[i]        = v[minIndex];
            v[minIndex] = temp;
        }
    }

Then, do the Initializing of item set combination

    private static void initialization()
    {
        /**
         * Make a greedy choosing
         * Take as much as first item, then second then continue...
         */
        int[] combination = new int[w.length];
        for (int i=0;i<w.length;i++)
        {
            int maximum = maxWeight/w[i];
            combination[i] = maximum;
            maxWeight = maxWeight - (maximum*w[i]);
        }

        /**
         * Assume the greedy choice taken is maximum set
         */
        maxSet = new int[combination.length];
        copyAllArrayValueTo(combination, maxSet);

        /**
         * Calculate the value of maximum set taken
         */
        int currentValue = 0;
        for (int i=0;i<maxSet.length;i++)
        {
            currentValue = currentValue + (maxSet[i]*v[i]);
        }
        maxValue = currentValue;
    }

And the final step of algorithm, Reduction and Expansion Move

    private static void reduceAndExpand()
    {
        /**
         * Make a copy of maximum set to be reduced and expanded
         */
        int[] set = new int[maxSet.length];
        copyAllArrayValueTo(maxSet, set);

        /**
         * Reduction and Expansion Step Loop Here
         * Loop until the all of the set is 0
         */
        boolean flag = true;
        while (flag)
        {
            /**
             * Reduction Move
             * Seek the least significant (not zero) digit
             */
            int leastSignificant = set.length-1;
            for (int i=leastSignificant;i>=0;i--)
            {
                if (set[i] != 0)
                {
                    leastSignificant = i;
                    break;
                }
            }

            /**
             * Reduction Move
             * Decrement the least significant digit or
             * set it to 0 (zero) if it's on last position
             */
            if (leastSignificant == set.length-1)
            {
                maxWeight = maxWeight + (set[leastSignificant]*w[leastSignificant]);
                set[leastSignificant] = 0;
            }
            else
            {
                maxWeight = maxWeight + w[leastSignificant];
                set[leastSignificant]--;

                /**
                 * Expansion Move
                 * Take a greedy choosing for items on right of
                 * least significant digit
                 */
                for (int i=leastSignificant+1;i<set.length;i++)
                {
                    int maximum = maxWeight/w[i];
                    set[i] = maximum;
                    maxWeight = maxWeight - (maximum*w[i]);
                }

                /**
                 * Calculating the value of new set
                 */
                int currentValue = 0;
                for (int i=0;i<set.length;i++)
                {
                    currentValue = currentValue + (set[i]*v[i]);
                }

                /**
                 * Replace the optimum set if
                 * the new set better
                 */
                if (currentValue > maxValue)
                {
                    maxValue = currentValue;
                    copyAllArrayValueTo(set, maxSet);
                }

            }

            /**
             * Loop terminator
             * Check if the set is 0
             */
            int itemCount = 0;
            for (int i=0;i<w.length;i++)
            {
                itemCount = itemCount + set[i];
            }
            if (itemCount == 0) flag = false;
        }
    }

Don’t forget the main method and other supporting methods….

    public static void main(String[] args)
    {
        if (!getData()) return;         //getting data from user
        preProcessing();                //ascending sort by ratio
        initialization();               //first greedy choosing
        reduceAndExpand();              //seek for more optimum set

        System.out.println(maxValue);
    }

    private static void copyAllArrayValueTo(int[] source, int[] dest)
    {
        for (int i=0;i<source.length;i++) dest[i] = source[i];
    }

Source and References

  1. University of Melbourne, Australia

DataGridView DataSource C# Source Code

How to fill DataGridView items on c# if we’re connect using OleDbConnection?

We’re gonna use DataSet for filling the DataGridView.. Here’is the example…

The information about variables and objects used is

  1. dataGridView1 –> DataGridView GUI Object from Toolbox
  2. Program.con –> OleDbConnection (using System.Data.OleDb)
  3. combo_produk_id –> ComboBox GUI Object from Toolbox
        private void Item_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            DataSet ds = new DataSet();

            Program.con.Open();
            
            OleDbCommand cmd = Program.con.CreateCommand();
            cmd.CommandText = "SELECT * FROM produk";

            OleDbDataReader reader = cmd.ExecuteReader();
            combo_produk_id.Items.Clear();
            while (reader.Read())
            {
                combo_produk_id.Items.Add(reader.GetValue(0));
            }

            Program.con.Close();

            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
            adapter.Fill(ds);
            
            dataGridView1.DataSource = ds.Tables[0];
            
        }