Friday, November 25, 2022

Coding while sleep deprived

Today I went to the CodeWars website. I was greeted with a little challenge.

Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.

Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case.

Keep in mind that I didn't sleep last night, and as I write this it's 7:15am. I'm cranky, tired, sleep deprived, and I can't sleep.

Well, what could a developer like me do in such a situation. The "chalenge" was super easy.

Less than a minute I banged up the following function:


var countBits = function(n) {
  if (n < 0)
    throw new Exception();
  
  var cnt = 0;
  while (n > 0) {
    cnt += (n & 1) == 1 ? 1 : 0;    
    n = Math.floor(n / 2);
  }

  return cnt;
};

Passed the tests with flying colors.

Why did I use Math.floor instead of a simple bit shift (>>)?

Simple. Because at the CodeWars website, this little code would run on JavaScript and the bit shift operation returns a 32-bit value, and I wanted to be sure that the function could operate with 64-bit values.

Thursday, November 24, 2022

Python Coding Puzzle

 Yesterday, I participated in a virtual event: Turing Jump Start for Python.

During the event it was proposed a coding puzzle, which the participants who wanted could try their hands at. I did try, and I'm posting my solutions here.

The puzzle was composed of two problems.

  • In one problem it was asked that we calculate the nth element of, what was called in the puzzle, a “Gibonacci” sequence. This sequence was similar in formation with the Fibonacci sequence in the sense that both sequences were made by an arithmetic operation on the previous two numbers.
  • The difference between the two sequences is that while the most famous one uses addition to generate its numbers, the Gibonacci sequence uses subtraction. Other than that, they are identical in its formation.
  • The other problem was to check if given a round of games everybody played against everybody. The problem was a little more complicated than that, but it's enough for now.
Here are my solutions:

Gibonacci Sequence

from typing import List

def solution(n: int, x: int, y: int) -> int:
	#
	# First let's deal with the obvious
	#
	if (n < 0):
		raise Exception("Invalid argument")
	if (n == 0):
		return x
	if (n == 1):
		return y

	#
	# Calculate the third "gibonacci" number
	#
	n1 = y - x
	n2 = n1 - y
	if (n == 2):
		return n1

	#
	# Follow the progression
	#
	# I'm sure that there might be a mathematical way to calculate
	# the nth "gibonacci" number, just like there is a mathematical 
	# way to calculate the nth Fibonacci number.
	#
	# I just don't want to spend the time to develop such calculation.
	#
	# To with, though, the nth Fibonacci number is calculated by:
	#
	# math.floor ( ( ( (1 + math.sqrt(5)) / 2 ) ** n - ( (1 - math.sqrt(5)) / 2 ) ** n ) * ( 1 / math.sqrt(5) ) )
	#
	for n in range(n - 3):
		n2 = n2 - n1
		n1 = n2

	return n2

if __name__ == '__main__':
	n = int(input())
	b = int(input())
	d = int(input())
	print(solution(n, b, d))

Player Pairs Problem

def solution(m: int, n: int, games) -> bool:
	#
	# If I understood the problem, games contains a list of lists.
	#
	# Each list in games represents one game, where the first
	# half of the list is one team and the second half od the list
	# is another team.
	#
	# For instance: [1, 2, 3, 4, 5, 6]
	#           one team <--|--> another team
	#
	# So I need to find if everybody played against everybody.
	#
	# On the second example [[1, 2, 3, 4], [4, 3, 1, 2]] = False
	# I understand that the first game was players [1, 2] x players [3, 4]
	# and the second game was players [4, 3] x players [1, 2], which
	# means that it was the 'same' game, meaning there were no variaton of 
	# players.
	#
	# On the third example [[1, 2, 3, 4], [1, 3, 2, 4]] = True
	# I understand that the first game was players [1, 2] x players [3, 4]
	# and the second game was players [1, 3] x players [2, 4], which
	# means that there were 'different' games.
	#
	# However, the problem asks to check "all pairs of players played 
	# against each other".
	#
	# Hold on, let me examine the second example again.
	#
	# We have for four players we have the following pairs:
	# (1, 2) (1, 3) (1, 4) (2, 3) (2, 4) (3, 4)
	#
	# The first game on the second example is [1, 2] x [3, 4],
	# which generates the pairs of players (1, 3) (1, 4) (2, 3) (2, 4)
	#
	# Meaning then that the round represented by the example generated 
	# only four pairs of the possible six. Therefore not everybody played
	# aginst everybody.
	#
	# All right, I think I see it now.
	#

	# 
	# Generate the pair of players
	#
	pairs = {}
	for a in range (1, m):
		for b in range(a + 1, m + 1):
			pairs[(a * 100000) + b] = 0

	#
	# Iterate through the games
	#
	k = int (m / 2)
	for g in games:
		#
		# Mark the pairs of the game
		#
		i = int(0)
		while (i < k):
			j = k
			while (j < m):
				s = sorted({ g[i], g[j] })
				pairs[(s[0] * 100000) + s[1]] = 1
				j = j + 1
			i = i + 1

	#
	# Check if there are any pair that didn't play
	#
	for p in pairs:
		if (pairs[p] == 0):
			return False

	return True

if __name__ == "__main__":
	m = int(input())
	n = int(input())
	mtx = [[int(val) for val in pair.split()] for pair in input().strip().split(',')]

	output = solution(m, n, mtx)
	if (optput == True):
		print("true")
	else:
		print("false")

Edited to add:
After posting this solution, someone pointed to me that the Gibonacci function could be optimized. That the sequence was cyclic and therefore did not need to be calculated further than the cycle. As soon as I have a little time on my hands I'll update the code here.

Labels: , ,

Wednesday, November 23, 2022

Codility Award

I just got a virtual certificate.


 

Codility

Today, I was sent a link to Codility, a site for software developers.

On it's frontpage they ask  you to improve a little JavaScript function that calculate a specified Fibonacci number, complaining that the function takes a long time to do so.

Here's the original function at the site:

var yourself = {
    fibonacci : function(n) {
        if (n === 0) {
            return 0;
        } else if (n === 1) {
            return 1;
        } else {
            return this.fibonacci(n - 1) +
                this.fibonacci(n - 2);
        }
    }
};
  

And here's how I improved it:

var yourself = {
    fibonacci : function(n) {
        if (n === 0) {
            return 0;
        } else if (n === 1) {
            return 1;
        } else {
            return Math.floor(
                    (
                     (Math.pow(((1 + Math.sqrt(5)) / 2), n)) - 
                     (Math.pow(((1 - Math.sqrt(5)) / 2), n))
                    ) *
                     (1 / Math.sqrt(5))
                   );
        }
    }
};

Sunday, November 20, 2022

Back into the fold

For more than the last ten years, I've been offline.
Not by choice.
The reasons for that are... complicated. 
I could tell you, but I'd have to kill you.
And as I don't want to commit genocide, I'll refrain myself from talking.
But, after this very long hiatus, I'm back into the fold.
Older and, I hope, wiser.
Returning after this long away from what was once called the "Information Super Highway," I realized that I lost a lot of things -- digital, electronic things.
I lost my email, my site, my blog, pretty much my digital life. And I'm struggling to get it back.
This blog is proof that I got something back. Every post in this blog prior to this date is a recuperated post from my previous (digital) life.
My former email, I believe, is gone for good. I could not recuperate for the life of me. Part of it is my fault. I had two different emails: one on Google and another one on Yahoo; and I set each other as recovery emails, setting the Google one for Yahoo and the Yahoo one for Google. And now I'm stuck in a loop where I can't reach either.
Other than the few blog entries I recuperate here, the only other item from my previous (digital) life I recovered was my StackOverflow account.

Tuesday, October 11, 2011

Monopoly and Thoughts

Reading this article several things came to mind. I live in Brazil and the word "monopoly" has a whole different meaning here. Let me explain it a bit. Although semantically "monopoly" means the same as in US, UK, or any place, most of brazilian monolopies were govenrment granted to "protect" the national industries.

Back in the 70's and 80's, and for part of the 90's, our telephone services wereprovided by state operated companies. Huge white elephants that could only operate because the government droped a buckload of tax money every time. Just to give you an idea, a phone line could be places as an asset on your income tax form. Back in those days if you needed a phone line, you could buy on the parallel market for something around $10,000 up to $50,000, depending on location.

In the 90's most of those government issued monopolies started to be broken down, by privatization of the state companies, generating better prices and services. Nowadays, any person can buy a mobile phone line for something like $5. And if you're willing to sign a 12 months agreement, you'd also could get the phone for free.

Anyway, back to the case at hand, when I see a "monopoly" that was built out of the benefits that a certain company provide to the users, and the success of a private company, I do get a bit mesmerized with it. To most brazilians, older than 35 years old, this is an almost alien concept. Almost.

As the author of the article suggests, there isn't a single "monopoly" on the internet, more like several different ones, on different segments. But the problem is, most of the companies that places their business on the internet, be them big or small, fail at one basic thing. The world isn't their own backyard.

Is Amazon a monopoly? Well, they might be in US or UK, but they don't sell everything in their catalog to Brazil. Heck, the S&H alone sometimes is twice the price of the item.

Saturday, September 24, 2011

Kindle for Android

After a short talk with my wife about reading books on mobile, I decided to take a look on the Android version of the Kindle app. After a quick browse through the Android Market I found the application, and reading the reviews I came up with the following thought: Kindle for Android is that kind of app that is a love it or hate it. For what I could gather, the app won't uninstall and will update itself even after explicitly selecting the option NOT to. Because of this I got really wary of installing it on my mobile. Therefore I'll be looking for another e-book reader.

Rant on StackOverflow

OK, there's no place to post this on S.O. so I'm placing here.

For starters this is a rant.

I've been using StackOverflow ever since Joel told about it on his late blog. And I'm a huge fan of the site, and have been a strong supporter, and advocate.

However, even though I'm thrilled with the success that is S.O., I've been noticing of late a crescent amount of silly question posted by first time users.

I want to make crystal clear that I don't mind helping newbies, and people who is learning, but c'mon, ask a question that Google can have it for you in less time that it takes for you to write and post the question?

A recent example, someone asked how to fill out a SELECT tag using PHP reading the information from a table. The reputation of the user: 1.

The problem with this kind of posts is that serious, sometimes job-treatening, questions are missed by people willing to answer because the barrage of siliness that pushes the just posted serious question to the page 2 or even 3.

/rant

Friday, August 5, 2011

Why Brazilian Internet rules MUST change!

For those who doesn't know I'm currently living in Brazil, and just read a message from Abranet that simply got me really pissed off.

The message, freely translated, is as follows:

Why Inernet rules must not change

Abranet - Internet Brazilian Association - publicly manifests its surprize and outrage with the information published at the press that the [Brazilian] government, through Ministério das Comunicações (Secretary of Communications), sent to Anatel (Bazilian FCC) requesting comments on substantial changes in the rules that governs brazilian Internet.

This changes, that would revoke the [Anatel's] Norm #4 from 1995, will greatly affect the Internet market, because it will eliminate the possibility of Internet Service/Content Providers to claim from telecommunication operators the same treatment in relation to the operator's own ISPs.

The current regulation was and is fundamental to mantain the growth of brazilian Internet, because it allows competitivity, low prices, variety and quality in content providing witin national territory. Also, the proposed changes suggests a substantial increat in taxes, by treating Internet as a simple telecommunication service and, therefore, subject to the charge of ICMS [brazilian tax on merchandize and services]. In pratice, it puts in risk the survival and the future of a relevant sector to the country.

Abranet, that was and always will be at disposal of the [Brazilian] government and the society to discuss the subject open, transparent and democratically, refutes any kind of atitude that disdains the good sense and does not listen all the important playes in the sector. Abranet trusts that the discussion, essential in a democratic society, still will be done, and by legally represent the sector, understands that it can give fundamental contributions to the interest of millions of Unternet users in Brazil.

This message, posted in all major newspaper in Brazil today, gave me a stomachache.

First of all, Brazil has one of the most expensive, monopolistic, and slow Internet connection in the free world.

Second, the proposed changes that the message talks about is that, if approved, the Internet Service Providers in Brazil will be forced to deliver a minimum quality and speed of the Internet connection they serve to their clients. Currently, there is no minimum set of quality that the ISPs must adhere to, although there is a common understanding among them that they need to deliver at least 10% of the agreed connection speed.

Yes, you read it right. Nowadays, when you hire an ISP to provide you with, say a 1Mbps Internet connection, the ISP need to deliver only 100Kbps to be on the up and up with their agreement, not much better than a 56Kbs dial-up connection.

Again, yes, you read it right. In Brazil the ISPs thinks that a 1Mbps connection is speed IS a broadband connection. Some providers even say that a broadband connection can have a speed as low as 256Kbsp.

So let me present you with a small comparison on ISP across the world and you'll see that Brazil has one of the most expensive Internet connection.

To ensure fairness the tables below were compiled with the fastest connection rate I could find on each of the providers below, in a reasonable amount of time, by no means this is an extensive research of Internet prices. The tables are sorted by the average price per Mbps.

The prices below compiled some of the Brazilian ISPs that offer Inetenet connection in major cities, their prices were converted to dollars by the exchange rate of Aug, 5th, 2011.

SpeedProviderPrice/MonthPrice/Mbps
100Mbps TVA 145.131.45
100Mbps NET 252.462.53
100Mbps GVT315.593.16
20MbpsOi82.004.10
8MpbsTelefonica56.757.09
As a comparison, below there are a few of the prices of the Internet Service Provider prices among the world. All prices were converted to dollars by the exchange rate of Aug, 5th, 2011.

SpeedProviderLocationPrice/MonthPrice/Mbps
200MpbsNTTJapan69.570.34
40MpbsBTUK45.901.15
150MpbsVerizonUSA194.991.30
25MpbsBellCanada 64.18 2.56

Thursday, July 21, 2011

Unable to read Code Analysis output report

I've came across a strange error today.

After compiling my code, Visual Studio reported the following error:

Unable to read Code Analysis output report. Make sure that the directory is writable (default is the project output directory).

A search on the net brought nothing that could help me solve this problem, so I decided to do some tests.

First of all, the setup of my application and developer environment: VS 2010, running on Windows 7 - 64bits edition Simple web application and console application in a single solution What prompted the error was that I wanted to use the IntelliTrace to help me debug my application, and to do so the application needed to be compiled against a x86 cpu, instead of the generic Any CPU.

To achieve this, I used the Configuration Manager to create a specific configuration for the x86, therefore making the pairs Debug/x86; Debug/Any CPU; Release/x86 and Release/Any CPU.

After a cleaning the solution and recompiling the application, I got the error when compiling against the x86 configuration.

Then, I selected the Any CPU configuration and the compilation went smoothly as it should have been.

I have no idea the true cause of the error, but I believe that it has something to do with the fact that when compiling against a x86 the output folder is setup automatically to something like:

bin\x86\Debug


Instead of the usual

bin\Debug


Because of this, I think that the Code Analysis is searching only the bin\Debug folder instead of the proper folder for the compiled assembly.

Friday, June 24, 2011

The shortcomings of NOT living in USA!

I'm not sure if I ever exposed this here, but currently I'm not living in US, even though much of my daily dealings involve US in one way or another, be it a client or supplier.

After all we live in a connected world, specially after the Internet.

Today I got flabbergasted with the GameStop intenert store.

I went there to pre-order two games that are due this fall: Batman: Arkham City; & Assassin's Creed: Revelations Both of them about $50 at the store.

So I went right ahead, added the games to the virtual shopping cart and proceeded to checkout.

There I got stunned. They attempted to charge me $120 for shipping and handling ($60 for each game).

Yep! You read right SIXTY dollars for a fifty dollars merchandize. A whooping 120% surcharge. Just because I'm currently not living in USA.

And when you start comparing things, like the minimum amount they charge to an ordinary (up to 7 days) delivery in the US is $2, you get a mind blowing 3,000% difference between charges.

To add insult to injury, the USPS lists an International Flat Rate box - perfect to send games overseas - for about $14.

I send a very angry letter to them to let they know that the world isn't only the USA.