Assembly: The very first date!

Today, we wrote and ran our first assembly program. To be honest, since we are used to coding in higher level languages, it seems getting used to assembly will not be easy. However, even though it may get annoying, it is fun!

We run our code at Hippy simulator. It simulates a M6800 processor. Despite the fact that we have not learned loops and conditionals yet, I was too curious to wait for the next lectures. Therefore, I tried to write a very simple program that has very basic usage of conditionals and loops. Since I am not familiar with the instructions yet, it took more than necessary time. But it was worth every minute of it and I think I will get along well with assembly.

Now I am representing the source of my program. Thanks to the Hippy, I do not have to load op-codes to memory manually. It compiles the mnemonic codes and loads the op-codes to the memory. I will not explain what code does, actually it may be a good exercise if you try to understand. Well, label names will be very helpful.

P.S: I know this code can be shortened. I was too lazy to improve it and do not forget the fact that this is my first program.

LDAA 100H
LDAB 105H

CBA
BGE AGRE
BRA BGRE

AGRE: SBA
CBA
BGE AGRE
CMPA #0000H
BEQ DIVISIBLE
BRA NONDIVISIBLE

LDAA 105H
LDAB 100H
BGRE: SBA
CBA
BGE BGRE
CMPA #0000H
BEQ DIVISIBLE
BRA NONDIVISIBLE

DIVISIBLE: LDAA #1H
STAA 110H
SWI

NONDIVISIBLE: LDAA #0H
STAA 110H
SWI

Tags: ,

Comments (1)

TopCoder SRM 492 – TimeTravellingCellar [C++]

Since I am very new to “algorithm” world and neither have enough knowledge nor IQ to solve harder questions, I am trying to solve TopCoder DIV II – Level I questions. They are usually very easy to solve. They do not need any special algorithm knowledge, basic coding approach does work.

I will try to explain some of the questions that i solved. I start with the TimeTravellingCellar problem. You can find the problem statement here.

Well if you look at the constraints, you realize that you can solve problem by brute force approah. However i came up with a different and a better solution.

It is clear that in order to find the answer, we need to find to find the max profit and the min decay. By using this simple realization, we can solve the problem in O(N) time. Implementation is even easier than the realization, as it only involves finding maximum and minimum. The only trick is that you cannot time travel in the same cellar, meaning if the cellar with the highest profit contains the lowest decay, you should ignore the cellar with the highest profit while finding the lowest decay profit.

I have implemented my solution in C++.

	int max(vector<int> profit)
	{
		int place=0;
		int maxi = 0;
		for(int i = 0; i<profit.size();i++)
		{
			if(profit[i] > maxi)
			{
				maxi = profit[i];
				place = i;
			}
		}	
 
		return place;
	}

The above function simply returns the index of the max element. It is easy to calculate that this code runs in O(N) time.

int min(vector<int> profit,int aa)
		{
		int place=aa;
		int maxi = 10001;
		for(int i = 0; i<profit.size();i++)
		{
			if(profit[i] < maxi)
			{
				if(i != aa)
				{
				maxi = profit[i];
				place = i;
				}
			}
		}	
 
		return place;
	}

Well this is the same as findMax function. The only trick is that I pass the index of max profit element in order to ignore it while finding the lowest decay element. Nothing special.

And in the actual function, I simply substract the lowest decay from the highest profit value. The code as a whole looks like this:

#include <vector>
#include <set>
using namespace std;
 
class TimeTravellingCellar
{
	public:
	int max(vector<int> profit)
	{
		int place=0;
		int maxi = 0;
		for(int i = 0; i<profit.size();i++)
		{
			if(profit[i] > maxi)
			{
				maxi = profit[i];
				place = i;
			}
		}	
 
		return place;
	}
 
	int min(vector<int> profit,int aa)
		{
		int place=aa;
		int maxi = 10001;
		for(int i = 0; i<profit.size();i++)
		{
			if(profit[i] < maxi)
			{
				if(i != aa)
				{
				maxi = profit[i];
				place = i;
				}
			}
		}	
 
		return place;
	}
 
	int determineProfit(vector<int> profit, vector<int> decay)
	{
		int maxi = max(profit);
		int mini = min(decay,maxi);
 
		return profit[maxi] - decay[mini];
	}
};

After submitting the solution, I have found a bug in my program. Consider the situation: profit = { 888, 889, 100 }, decay = { 100, 1, 97 }. Let’s simulate what my program will do: It will find position of max element which is 889, then it will find position of min element. However, while finding the min element, it will return 97 due to ignoring second cellar. Finally it will return the answer as 889 – 97. However, this is not the best situation. The best profit we can get is 888 – 1. This situation happens when the lowest decay and highest profit is at the same cellar. This bug can be easily solved by a if statement, so I will not correct it now.

As you see, even the easiest problems can contain painful corner cases. If you find a bug in my solution, feel free to inform me.

PS: Sorry for the bad indentation. WP and Copy-Paste are responsible for this!

Tags: , , ,

Leave a Comment

The Dreamers

‘‘… and you, Marcus, you have given me many things; now I shall give you this good advice. Be many people. Give up the game of being always Marcus Cocoza. You have worried too much about Marcus Cocoza, so that you have been really his slave and prisoner. You have not done anything without first considering how it would affect Marcus Cocoza’s happiness and prestige. You were always much afraid that Marcus might do a stupid thing, or be bored. What would it really have mattered? All over the world people are doing stupid things … I should like you to be easy, your little heart to be light again. You must from now, be more than one, many people, as many as you can think of …’’

– Karen Blixen

Tags: , ,

Leave a Comment

ADTs : Stacks

As an exercise, i will design and implement my own stack ADT.

First of all we need to build necessary structures.

The Head structure will contain a counter and a pointer to stack nodes.

The node structure will contain a data pointer and a node pointer.

typedef struct node2
{
   void *dataPtr;
   struct node2 *nodePtr;
} NODE;
 
typedef struct
{
   int count;
   NODE *top;
} STACK;

We have constructed two structures: STACK structure will be the head of the stack. The head structure has a NODE pointer to the top of the stack and an integer to hold the number of the nodes. NODE structure will hold the given data. And of course, it has a link to another node.

Since we have constructed the structures, we can start to implement the operations.

Let me talk about the operations that i will implement. I am going to implement create, push and pop operations. Push adds data to the stack and pop retrieves data. As you know, all the operations affect the top of the stack.

In order to create a stack, we need to allocate the necessary memory and then we must update the head node:

STACK *createStack(void)
{
   STACK* stack;
 
   stack = (STACK*)(malloc(sizeof(STACK));
 
   if(stack)
   {
      stack->count = 0;
      stack->top = NULL;
   }
 
   return stack;
}

This one is easy to explain. We simply allocate memory for the head node and if allocation is done successfully, we simply set the counter as zero and pointer as NULL due to having no items at the stack.

After successfully creating the stack, the next goal is adding data to the stack. It is a little bit more trivial but still easy to understand. I will not explain the code, not now at least.

// it will return 1 if the operation is successful, 0 otherwise
// thanks to the generic pointer, any type of data can be pushed
int pushStack(STACK* stack, void* data)
{
    // allocate memory for the new node
    NODE* node;
    node = (NODE*)malloc(sizeof(NODE));
 
    // check if allocations is done
    if(!node)
       return 0;   
 
   // update the node
   node->nodePtr = stack-&gt;top;
   node->dataPtr = data;
 
   // update the head
   stack->top = node;
   (stack->count)++;
 
   return 1;
}

Now it is time to retrieve data.

void *popStack(STACK* stack)
{
    void *dataOut; //again, we love you generic pointer
 
   // empty stack cannot be popped
   if(stack->count==0)
     dataOut = NULL;
   else
   {
      dataOut = stack->head->dataPtr;
      NODE* temp = stack->top; // we dont want no leaks
      stack-&gt;top = stack->top>nodePtr;
      (stack->count)--;
      free(temp); // freedom <3
   }
 
return dataOut; 
}

I know i have not explained neither the code nor the ADT itself well enough. I will try to update this post -most probably i will not- but the whole point of this post is implementing stacks on my own and recapping it.

I have written all the code on wordpress and have not compiled. If you try any errors or if you have any questions, please feel free to ask or inform me.

Tags: , ,

Leave a Comment

It Might Get Loud!

It Might Get Loud

Buraya izlediğim her şeyi yazamayacak kadar tembel bir insan olduğumu kabul ettim ve çok nadir yazmaya başladım. Yalnız, arada yazılmak zorunda olan izlenenler çıkıyor ki şimdi de onlardan birisini yazacağım.

It Might Get Loud 2008 yapımı bir belgesel. Kendisi hayatınızda görebileceğiniz en “cool” açılışlardan birisine sahip. Daha başında “oo” diye giriyorsunuz filme.

Film Jimmy Page, The Edge ve Jack White etrafında geçiyor. White Stripes ve U2 seven veya dinleyen biri değilim, bu yüzden de genelde sadece Jimmy Page’li kısımları özel bir ilgiyle izledim. Ama söylemeden geçemeyeceğim, jack white da sağlam bir herifmiş.

Jack White arkadaşımız 10 çocuklu bir ailede yetişmiş. Ufacık bir odası varmış ve odasındaki müzik aletlerinden yer kalmadığı için yatağını dışarı çıkarmış. Odasında yerde yatıyormuş. Müzik aşkı takdir edilesi. Ayrıca filmde çok güzel bir cümle söylüyor: “Never wanted to play guitar, ever. Everyone plays guitar, whats the point?”. Şu everyone gürühuna dahil olamayacak kadar tembel olmam beni çok derinden yaraladı.

Jimmy Page hakkında ise söylenecek çok bir şey yok. Diğer ikisinin babası yaşında olmasına rağmen ikisini de ezip geçiyor karizmasıyla. Mor pantolonla bile karizma herif, daha ne olsun! Hele bir “rumble” dinlerken air guitar çalışı var ki, hayran kalmamak mümkün değil. Youtube’da şöyle bir yoruma rastladım ve kesinlikle paylaşmalıyım: “Incredible! Jimmy Page playing air guitar is better than most people playing actual guitar!” Daha da doğru tarif edilemezdi. Ayrıca jimmy abimiz zamanında strat çalıyormuş, bilmiyordum valla.

Ayrıca filmin bir kısmında kendinizi sorguluyorsunuz resmen. Yaşadıkları zorlukları ve harcadıkları emekleri anlatıyorlar ve insan ister istemez sorguluyor kendisini. Jimmy Page abimiz 15 yaşında emekliliği düşünmüş, siz anlayın durumun ehemmiyetini. Zaten bu durumun bilimsel açıklaması bile var da, gene de “in your face” durumu yaşatıyor.

Daha da uzatmayayım. İzleyin izlettirin. Bu kadar gazdan sonra elime gitarı alıp çalışmam gerekiyordu belki ama malesef yarın vizem var. O yüzden bu gaz boşa gitmesin diye gelip buraya yazıyorum, belki tekrar okuduğumda alırım aynı gazı.

Yazıyı bitirirken de, akıllara kazınan şu şarkıyı paylaşıyorum:

Tekrar görüşene dek, kendinize güzel davranınız.

Tags: ,

Leave a Comment

Özgür Web Teknolojileri Günleri

Uzun bir sessizliği ardından, sessizliğimi gerçekten büyük bir olay için bozuyorum.

LKD ve Yucomp olarak çok ama çok güzel ve başarılı bir etkinlik gerçekleştirdik ve ben bundan bahsetmek zorunda hissediyorum kendimi.

Belki anlatılacak çok şey var ama uzatmaya çok da gerek yok diye düşünüyorum. Çok fazla kişi çok fazla emek verdi(k) ve karşılığını alabilmek bizi çok mutlu ediyor. Umuyoruz ki sizlerden gelecek olumlu ya da olumsuz eleştirilerle seneye daha da iyi bir etkinlik yapacağız.

Bu güzel etkinliğin ardından böyle güzel güzel şeyler yazmak pazartesi günü vizem olduğu gerçeğini ise değiştirmiyor malesef. Bu sebepledir ki şimdi uykuya gidiyorum. Boş bir zamanımda(fotolar geldikten sonra) bu post update edilecektir ve çok daha eğlenceli hale gelecektir diye düşünüyorum.

Hoşçakalınız.

Tags: , , ,

Leave a Comment

Personal Disorders — Oh Noes!

Yaptığım testin sonuçlarını reklamlarıyla beraber c p yapıyorum:

Disorder | Rating
Paranoid: Moderate
Schizoid: High
Schizotypal: Moderate
Antisocial: High
…Borderline: Low
Histrionic: Moderate
Narcissistic: High
Avoidant: Low
Dependent: Low
Obsessive-Compulsive: High

URL of the test: http://www.4degreez.com/misc/personality_disorder_test.mv
URL for more info: http://www.4degreez.com/disorder/index.html

Test gayet basit, anlamlı ve sonuçları da gayet tutarlı. High çıkan bozukluklarımı inceledim:  Schizoid personality disorder (SPD) is a personality disorder characterized by a lack of interest in social relationships, a tendency towards a solitary lifestyle, secretiveness, and emotional coldness. >> Mesela bu yalnız olma sebebim için harika bir bahane.

Obsessive–compulsive disorder (OCD) is an anxiety disorder characterized by intrusive thoughts that produce uneasiness, apprehension, fear, or worry, by repetitive behaviors aimed at reducing anxiety, or by a combination of such thoughts (obsessions) and behaviors (compulsions). >> OMGWTF???

Antisocial ve narsisstic olayını tahmin edebiliorz zaten.

Valla kendimi iyi hissettim bu test sayesinde.  Sorun bende değilmiş, hastaymışım meğersem sdfds.

Leave a Comment

UPEM – Ankara’ya Ziyaret

Uzun bir aradan sonra yazı yazıyorum ki bu önemli olay için bir şeyler yazmasam olmazdı.

Nedir önemli olay? ODTÜ’yü kazanamadık ama bir hafta da olsa ODTÜ’de ders görmeye hak kazandık :p  Ulusal Programlama Eğitim ve Yarışma Programı dahilinde Ankara’ya gidiyoruz.  İki ekiple orda olacağız. Beş gün boyunca hızlıca bir eğitimden geçeceğiz ve cumartesi günü de yarışmaya katılacağız.

Doğruyu söylemek gerekirse benim bulunduğum ekip biraz tecrübe için gidiyor. Gene de, iyi bir iş çıkaracağımıza inanıyorum. Diğer ekibimiz ise çok daha tecrübeli. Onlardan derece görmek sürpriz olmaz diye düşünüyorum.

Program hakkında daha ayrıntılı bilgiyi burdan alabilirsiniz. Beş günlük yoğun bir program ve sonrasında da yarışma var. Bize bol şans dileyiniz ve kendinize iyi bakınız.

Tags: ,

Leave a Comment

Char to Int Conversion in C

The programming thing has a lot of tricks and as a programmer, I like them very very much.

The latest trick that i have come across is converting a char digit to its integer value.

As you know, if you write something like this:

char num[11] = "0123456789";
int s = (int)num[0];
printf("%d\n",s);

It will not print 0, but instead it will print the ASCII value of ’0′.

While looking for a quick solution, I have seen this perfect trick at stackoverflow:

char num[11] = "0123456789";
int s = num[0] - '0';
printf("%d\n",s);

Since all the digits are consecutive at the ASCII Table, -supposing all the elements are digits- substracting the ASCII value of ’0′ from that digit’s ASCII value gives you the correct integer value of the digit.

All that I can say is: FASCINATING!

Tags: , ,

Comments (1)

Sansür Hakkında Bilinmesi Gerekenler

Uzun zamandır yazı yazmayan ben, sessizliğimi önemli bir olay için bozuyorum. Aslında tam olarak yazı yazacağım söylenemez, çünkü kendi düşüncelerime yer vermeyeceğim. Sadece bazı karışıklıkları gidermek amacıyla okumanız gerektiğini düşündüğüm yazıları söyleyeceğim.

Öncelikle “vergi” sebebiyle kapatılan youtube hakkında yazılmış bir yazı var. “Ama youtube da vergi vermiyor yeaaa” demeden önce okunması gerekiyor. Kendisi burda.

Ayrıca pek çoğumuzun yanlış bildiği bir şey var -ben de öğreneli çok olmadı-: Google’ın Türkiye ofisi bulunmakta. Kendisi google’ın diğer pek çok ülkedeki ofisleri gibi aracı görev görmekteymiş. Üstte verdiğim yazıda bunu güzelce açıklamışlar. Bunu takiben bir de google avukatlarının açıklaması var, isteyenler onu da burdan okuyabilir.

Unutmayalım ki sansüre karşı olan bizlerin derdi “youtube” değil. Bizim derdimiz “sansür”. Geçtiğimiz cumartesi Kadir Has Üniversitesi’nde çok güzel bir toplantı gerçekleştirildi, internetten de canlı yayınlandı. Bu gibi şeylere katılmadan ya da bunları izlemeden atıp tutmak çok kolay. Amaç sadece youtube’un tekrar açılması değil, şu anda erişilemeyen binlerce sitenin tekrar erişilebilir gelmesidir. Daha söylenecek çok şey olsa da, kendi fikirlerimi yazmamakta kararlıyım.

Sansüre karşı durmak isteyenler için şöyle bir şey de var:  Sansürsüzİnternet. Bir şeyler yapmak isteyenler bu bildiriyi imzalayabilir, mail grubuna katılıp sonraki adımlarda yer alabilir.

Aydınlık günler dilerim.

Tags: , ,

Leave a Comment