Many of the supermarkets here are playing tricks on the price tags. While the price tag displays $x.xx/lb, the receipt shows the price in dollars per kilograms. As a customer, we are always confused and hard to remember the listed price when we are reading the receipt. But why the supermarkets do that? 99 cents per pounds looks quite attractive on the price tag. People nowadays do not expect too much from a buck or so. When you enter a supermarket and see that one dollar, even less a dollar, can buy this, that and a lot, you cannot help buying all those good deals. Not until you get home and read the receipt, you find out it is actually $2.18 per kilogram. No! It is not under a buck. It is more than 2 bucks!
Well, you and I all know they are the same things. It is just a trick of the unit conversion. I wrote a little JavaScript program Unit Converter to help easily comparing things in different units. It does not cover everything. Instead, it just collect some of the most useful units we may use in daily basis.
For example, when you are travelling outside the country, you may not know whether the gas is too expensive if the price is listed as per litre instead of gallon, or vice versa. And you may not know whether you should wear T-shirt or coat if the temperature is forecast in a different unit of Fahrenheit or Celsius.
Bookmark this little online tool to make life simple -- Unit Converter.
Wednesday, April 21, 2010
Tuesday, April 20, 2010
C++ exercises: selection sort, bubble sort, insertion sort
Q: Consider the record declaration
struct Month { char name[10]; //name of a month
int monthnum; //number of days in the month
};
a) Write a function
void SortByName(Month months[], int n);
that sorts an array whose elements are of type month by comparing names (use C++ function strcmp). Also write a function
void SortbyDays(Month months[], int n);
that sorts the list by comparing the number of days in a month. Write a main program that declares an array containing all the months of the year and sorts it using both functions. Print each sorted list.
b) Note that sorting a list of months by number of days produces ties. When this happens a sorting method can use a secondary key to break ties. Write the function
void Sort2byDays(Month months[], int n);
that sorts the list by first comparing the number of days and, if a tie occurs, breaks the tie by comparing names. Use the function in a main program to print out an ordered list of all the months in the year, ordered by number of days.
struct Month { char name[10]; //name of a month
int monthnum; //number of days in the month
};
a) Write a function
void SortByName(Month months[], int n);
that sorts an array whose elements are of type month by comparing names (use C++ function strcmp). Also write a function
void SortbyDays(Month months[], int n);
that sorts the list by comparing the number of days in a month. Write a main program that declares an array containing all the months of the year and sorts it using both functions. Print each sorted list.
b) Note that sorting a list of months by number of days produces ties. When this happens a sorting method can use a secondary key to break ties. Write the function
void Sort2byDays(Month months[], int n);
that sorts the list by first comparing the number of days and, if a tie occurs, breaks the tie by comparing names. Use the function in a main program to print out an ordered list of all the months in the year, ordered by number of days.
#include <iostream>
using namespace std;
struct Month {
char name[10];
int monthnum;
};
// Selection sort.
void SortByName(Month month[], int n)
{
if (n < 2)
return;
Month hold;
int min_idx;
for (int i = 0; i < n - 1; i++)
{
hold = month[i]; // selected one to be exchanged with the min.
min_idx = i;
for (int j = i + 1; j < n; j++)
{
if (strcmp(month[i].name, month[j].name) > 0)
{
// Find the min one.
// Put to the first pos (index of i).
month[i] = month[j];
min_idx = j;
}
}
if (i != min_idx)
month[min_idx] = hold;
}
}
// Bubble sort.
void SortByDays(Month month[], int n)
{
if (n < 2)
return;
bool changed;
for (int i = n - 1; i >= 0; i--)
{
changed = false;
for (int j = 0; j < i; j++)
{
if (month[j].monthnum > month[j+1].monthnum)
{
Month tmpmon;
tmpmon = month[j];
month[j] = month[j+1];
month[j+1] = tmpmon;
changed = true;
}
}
if (!changed)
break;
}
}
// overload operator < for Month
bool operator<(const Month& mon1, const Month& mon2)
{
if (mon1.monthnum < mon2.monthnum)
return true;
else if (mon1.monthnum > mon2.monthnum)
return false;
// monthnum equal
if (strcmp(mon1.name, mon2.name) < 0)
return true;
else
return false;
}
// Insertion sort
void Sort2ByDays(Month month[], int n)
{
Month hold;
for (int i = 1; i < n; i++)
{
hold = month[i]; // the one to be inserted.
int j;
for (j = i; j > 0; j--)
{
if (hold < month[j-1])
month[j] = month[j-1]; // shift right. j-1 is reserved for "hold"
else
break;
}
month[j] = hold; // j is the position for what we selected.
}
}
void PrintMonths(Month month[], int n)
{
for (int i = 0; i < n; i++)
{
cout << month[i].name << " " << month[i].monthnum << endl;
}
cout << endl;
}
int main()
{
const Month months[12] = {
{"January", 31},
{"February", 28},
{"March", 31},
{"April", 30},
{"May", 31},
{"June", 30},
{"July", 31},
{"August", 31},
{"September", 30},
{"October", 31},
{"November", 30},
{"December", 31}
};
Month mn[12];
cout << "--- Original ---" << endl;
memcpy(mn, months, sizeof(mn));
PrintMonths(mn, 12);
cout << "--- SortByName ---" << endl;
memcpy(mn, months, sizeof(mn));
SortByName(mn, 12);
PrintMonths(mn, 12);
cout << "--- SortByDays ---" << endl;
memcpy(mn, months, sizeof(mn));
SortByDays(mn, 12);
PrintMonths(mn, 12);
cout << "--- Sort2ByDays ---" << endl;
memcpy(mn, months, sizeof(mn));
Sort2ByDays(mn, 12);
PrintMonths(mn, 12);
return 0;
}
Monday, April 19, 2010
C++ exercises: exchange sort
Q: Write an exchange sort function to sort the list in descending order.
#include <iostream>
using namespace std;
void ExchangeSortDesc(int a[], int sz)
{
if (sz < 2)
return;
for (int i = 0; i < sz - 1; i++)
{
for (int j = i + 1; j < sz; j++)
{
if (a[i] < a[j])
{
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
}
int main()
{
int a[] = {1, 2, 3, 10, 8, 7, 9, 5, 6, 4};
#define ITMES_NUM (sizeof(a)/sizeof(int))
// output original
for (unsigned int i = 0; i < ITMES_NUM; i++)
{
cout << a[i] << " ";
}
cout << endl;
// sort it
ExchangeSortDesc(a, ITMES_NUM);
// output result
for (unsigned int i = 0; i < ITMES_NUM; i++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}
Sunday, April 18, 2010
C++ exercises: tabular encrypt
Q: A string of text can be encrypted using a tabular mapping that associates each letter of the alphabet with a unique letter. For example, the mapping
abcdefghijklmnopqrstuvwxyz ==> ngzqtcobmuhelkpdawxfyivrsj
maps "encrypt" to "tkzwsdf".
Write a program that reads text until end of file and outputs the encrypted form.
abcdefghijklmnopqrstuvwxyz ==> ngzqtcobmuhelkpdawxfyivrsj
maps "encrypt" to "tkzwsdf".
Write a program that reads text until end of file and outputs the encrypted form.
#include <iostream>
#include <string>
using namespace std;
int main()
{
const char s[] = "abcdefghijklmnopqrstuvwxyz";
const char d[] = "ngzqtcobmuhelkpdawxfyivrsj";
while (1)
{
string st;
cout << "Input a word: ";
cin >> st;
cout << endl << "Encrypted as: ";
for (unsigned int i = 0; i < st.size(); i++)
{
for (unsigned int j = 0; j < sizeof(s); j++)
{
if (s[j] == st[i])
{
// found, output encrypted char
cout << d[j];
}
}
}
cout << endl << endl;
}
return 0;
}
Saturday, April 17, 2010
C++ exercises: Pig-latin
Q: Input a series of words until end of file, converting each one to Pig-latin. If the word begins with a consonant, move the first character of the word to the last position and append "ay". If the word begins with a vowel, simply append "ay". for example,
Input: this is simple
Output: histay isay implesay
Input: this is simple
Output: histay isay implesay
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
if (argc < 2)
{
cout << "Usage: " << argv[0] << " <input_file>" << endl;
return -1;
}
fstream f(argv[1]); // open the input file
string s;
string vowel("AEIOUaeiou");
while (!f.eof())
{
f >> s; // read one word
if (vowel.find(s[0]) == string::npos)
{
// begins with a consonant
s += s[0];
s += "ay";
s.erase(0, 1);
}
else
{
// begins with a vowel
s += "ay";
}
cout << s << " ";
}
return 0;
}
Friday, April 16, 2010
Linux: use awk to help generate XML file
We have a text file product_desc.txt like this:
awk '{print "<"$1">"$2"</"$1">"}' product_desc.txt
In the command, $1 refers to column 1 in file product_desc.txt, and $2 refers to column 2. The characters we want to output as is are put between quotes("").
The command will print the result on the screen. If you want to write it to a file, just use the redirection:
awk '{print "<"$1">"$2"</"$1">"}' product_desc.txt >product_desc.xml
name product1 size large weight 30lb price 10.00 quantity 100and we want to change it into XML format:
<name>product1</name> <size>large</size> <weight>30lb</weight> <price>10.00</price> <quantity>100</quantity>So we run command:
awk '{print "<"$1">"$2"</"$1">"}' product_desc.txt
In the command, $1 refers to column 1 in file product_desc.txt, and $2 refers to column 2. The characters we want to output as is are put between quotes("").
The command will print the result on the screen. If you want to write it to a file, just use the redirection:
awk '{print "<"$1">"$2"</"$1">"}' product_desc.txt >product_desc.xml
C++ exercises: DaysOfWeek
Q: Consider the enumerated type
enum DaysOfWeek {Sun, Mon, Tues, Web, Thurs, Fri, Sat};
Write a function
void GetDay(DaysOfWeek& day);
that reads the name of a day from the keyboard as a string and assigns the corresponding enum value to day. Also write a function
void PutDay(DaysOfWeek day)
that writes the enum value to the screen. Develop a main program to test the two functions.
enum DaysOfWeek {Sun, Mon, Tues, Web, Thurs, Fri, Sat};
Write a function
void GetDay(DaysOfWeek& day);
that reads the name of a day from the keyboard as a string and assigns the corresponding enum value to day. Also write a function
void PutDay(DaysOfWeek day)
that writes the enum value to the screen. Develop a main program to test the two functions.
#include <iostream>
#include <string>
using namespace std;
enum DaysOfWeek {Sun, Mon, Tues, Wed, Thurs, Fri, Sat};
void GetDay(DaysOfWeek& day)
{
string s;
cout << "Input a day: ";
cin >> s;
if ("Sunday" == s)
day = Sun;
else if ("Monday" == s)
day = Mon;
else if ("Tuesday" == s)
day = Tues;
else if (s.find("Wed") == 0)
day = Wed;
else if (s.find("Thu") == 0)
day = Thurs;
else if (s.find("Fri") == 0)
day = Fri;
else if (s.find("Sat") == 0)
day = Sat;
else
exit(-1);
}
void PutDay(DaysOfWeek day)
{
cout << "Day: " << day << endl;
}
int main()
{
while (1)
{
DaysOfWeek day;
GetDay(day);
PutDay(day);
}
return 0;
}
Thursday, April 15, 2010
C++ exercises: hex and decimal
Q: Write a program that declares three integer variables i, j, k. Input a value for i in decimal and values for j and k in hex. Print all three variables in both hex and decimal.
#include <iostream>
using namespace std;
int main()
{
int i, j, k;
cout << "input i(dec), j(hex), k(hex):";
cin >> i >> hex >> j >> k;
cout << "i: " << hex << i << "(hex) " << dec << i << "(dec) " << endl;
cout << "j: " << hex << j << "(hex) " << dec << j << "(dec) " << endl;
cout << "k: " << hex << k << "(hex) " << dec << k << "(dec) " << endl;
return 0;
}
C++ exercises: OctIn
Q: Write a function
void OctIn(unsigned int& n);
that reads a base 8 (octal) number and assigns it to n. Use OctIn in a main program that reads the following octal numbers and prints the decimal equivalents:
7, 177, 127, 7776, 177777
void OctIn(unsigned int& n);
that reads a base 8 (octal) number and assigns it to n. Use OctIn in a main program that reads the following octal numbers and prints the decimal equivalents:
7, 177, 127, 7776, 177777
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::oct;
void OctIn(unsigned int& n)
{
cin >> oct >> n;
}
int main()
{
unsigned int n;
cout << "Input an octal number: ";
OctIn(n);
cout << n << endl;
return 0;
}
Wednesday, April 14, 2010
Add a Gadget in Blogger.com
After login into Blogger.com, go to the dashboard of Blogger.com. Select "Layout" then "Page Elements". There are several places you can add a gadget.
If you are using a template without one or two "Add a Gadget" boxes and you want to add them back, you can do that by modifying the HTML on the "Edit HTML" tab. For example, if the "Add a Gadget" box below the title is missing and you want it, click "Edit HTML" tab and look for the following code in the <body> section of the code:
<b:section class='crosscol' id='crosscol' showaddelement='no'/>
and change the "showaddelement" attribute from 'no' to 'yes'.
Similar changes can be made to the other sections to show or hide the "Add a Gadget" boxes. After you change the code, do not forget to click the "SAVE TEMPLATE" button. ^_^
- right below the title and above the posts;
- the side bar;
- the footer;
If you are using a template without one or two "Add a Gadget" boxes and you want to add them back, you can do that by modifying the HTML on the "Edit HTML" tab. For example, if the "Add a Gadget" box below the title is missing and you want it, click "Edit HTML" tab and look for the following code in the <body> section of the code:
<b:section class='crosscol' id='crosscol' showaddelement='no'/>
and change the "showaddelement" attribute from 'no' to 'yes'.
Similar changes can be made to the other sections to show or hide the "Add a Gadget" boxes. After you change the code, do not forget to click the "SAVE TEMPLATE" button. ^_^
C++ exercises: BaseOut
Q: Write a function
void BaseOut(unsigned int n, int b);
that outputs n in the base b, 2 <= b <= 10. Print each number in the range 2<=n<=50 in base 2, 4, 5, 8 and 9.
void BaseOut(unsigned int n, int b);
that outputs n in the base b, 2 <= b <= 10. Print each number in the range 2<=n<=50 in base 2, 4, 5, 8 and 9.
#include <iostream>
using std::cout;
using std::endl;
void BaseOut(unsigned int n, int b)
{
int a[64]; // 64 may not be enough if n is bigger.
// Check the range of b.
if (b > 10 || b < 2)
{
cout << "Error: base out of range - " << b << endl;
return;
}
cout << n << " in the base " << b << ":";
// Calculate and store the result in a[].
size_t i;
for (i = 0; n > 0; i++)
{
if (sizeof(a) <= i)
{
cout << "Error: " << n << " is too big" << endl;
return;
}
a[i] = n % b;
n /= b;
}
// Output the result.
for (size_t j = 1; j <= i; j++)
{
cout << a[i-j];
}
cout << endl;
}
int main()
{
for (size_t i = 2; i <=50; i++)
{
BaseOut(i, 2); // i in the base 2
BaseOut(i, 4); // i in the base 4
BaseOut(i, 5); // i in the base 5
BaseOut(i, 8); // i in the base 8
BaseOut(i, 9); // i in the base 9
cout << endl;
}
return 0;
}
Wednesday, April 7, 2010
Firefox extension: new features of Take-A-Break
New features of Take A Break are added in version 1.1 to serve the feedbacks from you. It is already submitted to the official Firefox extensions website. Please give it a try. The new features are -
Sound Option
You can enable sound for the short break. When it is enabled, the extension will keep beeping while the icon is flashing, and stop beeping when the short break ends. So you can know when to open your eyes if you close your eyes during the short break. It is also useful for those users who focus too much on the content to notice the changing of the icon on the status bar, or those who does not show the browser's status bar at all.
The Sound Option is off by default -- some people may find it annoying. You can enable it by going to the Options page.
A More Fancy Reminder Window
A more fancy reminder window pops up to remind you a rest. It gives some suggestions -- with graphics -- of what you could do during the long break. If you like a simple and clean dialog instead, you can use the next feature.
Write Your Own Reminder Text
You can let the Reminder Window show the text you choose. Go to the Options page, check "Use My Text in Reminder" and write down your own text. When you enable this option, you get a no-frills dialog.
New Icons
Some people dislike the old set of icons. In this release, I use some new ones. I am not an artist, so don't expect too much. :)
A new online help for version 1.1 can be found here.
Thanks a lot to all of you for the reviews and suggestions. Your supports encourage me to keep on improving it.
Sound Option
You can enable sound for the short break. When it is enabled, the extension will keep beeping while the icon is flashing, and stop beeping when the short break ends. So you can know when to open your eyes if you close your eyes during the short break. It is also useful for those users who focus too much on the content to notice the changing of the icon on the status bar, or those who does not show the browser's status bar at all.
The Sound Option is off by default -- some people may find it annoying. You can enable it by going to the Options page.
A More Fancy Reminder Window
A more fancy reminder window pops up to remind you a rest. It gives some suggestions -- with graphics -- of what you could do during the long break. If you like a simple and clean dialog instead, you can use the next feature.
Write Your Own Reminder Text
You can let the Reminder Window show the text you choose. Go to the Options page, check "Use My Text in Reminder" and write down your own text. When you enable this option, you get a no-frills dialog.
New Icons
Some people dislike the old set of icons. In this release, I use some new ones. I am not an artist, so don't expect too much. :)
A new online help for version 1.1 can be found here.
Thanks a lot to all of you for the reviews and suggestions. Your supports encourage me to keep on improving it.
Subscribe to:
Posts (Atom)