Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Wednesday, February 18, 2015

DZone shortest code to print first 30 fibonacci numbers without using numbers

There's interesting challenge on Dzone website. The task is to print Fibonacci sequence for first 30 numbers in the format "order: fib number". Once constraint is that you can't use any numbers in the code. Shortest answer wins.
My take on that problem in Ruby is here (85characters):
[edit] During morning run I've realised that using array is just PITA and by getting rid of indexes for last and previous elements I can save some space (64 characters):
Code snippet - 30 fibonacci numbers without using numbers in Ruby on Snipplr

[edit] Since there was groovy solution with 64 characters I've shaved off another two getting down to 62.
Code snippet - 30 Fibonacci Numbers Without Using Numbers In Ruby(62) on Snipplr

Later when I read discussion they have dropped requirement to use : in the output so I decided to update solution and found another nifty trick to get rid of another two characters ending up at 58(60) chars which can be easily reduced to 57 by removing whitespace after p.

Monday, July 28, 2014

One-liners: Deformalize

Recently I needed quick hack for following situation. Given an input like this:
A 1
A 2
B 3
C 4
C 5
C 6
C 7
D 8

I wanted to generate following:
text A -p 1 -p 2
text B -p 3
text C -p 4 -p 5 -p 6 -p 7
text D -p 8

After some thought I have generated it with this awk one-liner.
cat file | awk '{ if (X==$1) { printf " -p "$2 ; } else { printf "\ntext " $1 " -p "$2 ; X=$1 } }'
What would you do? Is there an easier way ?

Friday, April 11, 2014

ENV is not a Hash but Object in Ruby

Recently I hit this funny problem in ruby, when trying to merge options to ENV. Although ENV supports most of Hash functions, it's not really Hash instance:
irb(main):001:0> ENV.class
=> Object
irb(main):002:0> env = { 'X'=>1 }
=> {"X"=>1}
irb(main):003:0> env.class
=> Hash
There are some useful methods missing from ENV like merge!
irb(main):004:0> ENV.merge(env)
NoMethodError: undefined method `merge' for #<object:0xb7f54814>
       from (irb):4
Workaround is simple enough, merge! hash manualy:
irb(main):012:0> env.each { |k,v| ENV[k.to_s]=v.to_s }
=> {"X"=>1}
irb(main):013:0> ENV["X"]
=> "1"

Wednesday, April 9, 2014

Work around core library class mocks/stubs in ruby

Just a short post about mocking/stubbing your Ruby functions. Let's have a class like this:
class ConfigurableClass
  attr_reader :option
  def configure_from_file(file)
    json = JSON(IO.read(file))
    @option = json['my']['option']
  end
end

One way to test this would be to mock IO.read with Mocha
describe ConfigurableClass do
 it "can configure from json" do
   data =  '{ "my": { "option" : "hello" } }'
     IO.any_instance.expect(:read).with("x.json").returns(data)
     cc = ConfigurableClass.new
     cc.configure_from_file("x.json")
     cc.option.should eq "hello"
   end
end

This is tricky if your code does IO.read anywhere else which you obviously don't want to mock. However with some refactoring code is much cleaner.
class ConfigurableClass
  attr_reader :option
  def read_config_file(file)
    IO.read(file)
  end

  def configure_from_file(file)
    json = JSON(read_config_file)
    @option = json['my']['option']
  end
end

Then in the rspec it's easy to mock only function specific to ConfigurableClass.
describe ConfigurableClass do
  it "can configure from json" do
    data =  '{ "my": { "option" : "hello" } }'
    ConfigurableClass.any_instance.expect(read_config_file).with("x.json").returns(data)
    cc = ConfigurableClass.new
    cc.configure_from_file("x.json")
    cc.option.should eq "hello"
end

Thursday, June 21, 2012

GoF design patterns reference card

Gang Of Four design patterns is probably most known developer book ever. As it is little too verbose on single patterns, people created reference cards for it. Most popular would probably be one at DZone. Recently I've tried to find one, that I can put on my Kindle and eventually found it on Google docs, so I've thought maybe I should share it.

Sunday, May 29, 2011

How to convert multi-page HTML e-book for Kindle

Recently I've got link to the interesting e-book Architecture of Open Source applications. Because I prefer to read books on my Kindle and there was no MOBI version I've decided to prepare it myself. Here is step-by-step guide on how to convert multi-page HTML to format suitable for Kindle on your Ubuntu/Debian/Other linux.

Getting data

First of all we need to get HTML/CSS and image files to local machine. On my machine it's as simple as:
$mkdir ~/aosabook; cd ~/aosabook
$wget -I en,images -nd -r -k -l 3 http://www.aosabook.org/en
We want to download all documents recursively but only from en and images directories, don't create directory structure to local copy and replace paths in html documents so they're locally referenced. For more details check man wget.

Convert to single HTML

Now we have all data downloaded in ~/aosabook and to check whether book is readable we just have to open file:///home/aosabook/ in browser.
Because the structure of the web is multi-page, we have to do additional step. Convert the multi page document into single page. I've used htmldoc utility for this. Run htmldoc and do following:
  • input tab
    • choose Document Type: Book
    • Use add files button to add all html files from ~/aosabook/
    • Select cover image
  • output tab
    • set output to file
    • set output path to ~/aosabook/aosabook.html
    • set output format to html
Play with some other options namely width (set it to 600px for kindle 3) and hit generate.

Convert to Mobi

In order to convert to MOBI format suitable for Kindle, I've just added generated aosabook.html as book to Calibre (you use calibre for your kindle management right?) and clicked on book to convert to Mobi and upload to device.

Thursday, November 27, 2008

C/C++ puzzler #2 - Is it typo ?

Ok, here is next C/C++ specific puzzler. Puzzler here is to guess, what will be result of program ?

  1. It won't compile

  2. It will compile, but it will segfault when we try to run it

  3. It will run and print 4 times 30

  4. Anything else you can think of



Highlight text bellow code to find out correct answer.


/* compile with cc -g -o test_typedef_sizeof test_typedef_sizeof.c */
#include <stdio.h>
#include <string.h>

typedef char name_t[30];

void fn(name_t value)
{
printf("%d\n", sizeof(name_t));
printf("%d\n", sizeof(value));
}

int main (void)
{
name_t aa;

printf("%d\n", sizeof(name_t));
printf("%d\n", sizeof(aa));

fn(aa);
return 0;
}



I'll just show you program output:

30
30
30
4

Is it not, what you have expected ? Fine, let's walk the program together. On entry to main() program prints sizeof(user defined type name_t), which has length of 30 chars. Next it'll print sizeof(instance of name_t) which again is 30 chars long. Then it calls function fn(instance of name_t), In fn() it prints sizeof(user defined type name_t) which is again 30 bytes. But when it tries to print sizeof(value) it prints 4, because arrays are passed as reference to first element in C/C++. And the sizeof(pointer) is 4 respectively 8 for 64 bit system.

Java EE factsheets

Stefan Jäger recently posted bunch of Java EE fact-sheets on his blog. Stefan created fact-sheets for: SF and SL session beans, MDB's and JMS, Transactions and security, and finally JPA. Very nice, and available as PDF downloads.

Thursday, October 30, 2008

C/C++ puzzler #1 - Where do you want to go today ?

First puzzler is in C/C++ and it is based on puzzler found in book Java Puzzlers by Neal Gafter and Joshua Bloch.
Problem:
We have following C program:
/* compile with: cc -g -o test_xxx test_xxx.c */
#include <stdio.h>
#include <stdlib.h>

int main (void)
{
printf("firefox.exe");
http://www.google.com;
printf(":new\n");
exit(0);
}

Options:
What will the program do:
a) print firefox.exe
b) run firefox.exe open http://www.google.com in new tab
c) fail to compile
d) other


Solution: (highlight to see)

First look at source, and you probably think that this couldn't compile. In fact it does. Real puzzler is, why does it compile. Problem seems to be in line http://www.google.com; But let's take a closer look. Is it problem ? It compile because of long forgotten feature of C, which is labels. (Except for kernel source, you'll find plenty of labels there ;) What compiler see is label http: followed by comment //www.google.com;

Puzzlers series

I guess everyone have been in situation when he/she has written code, which didn't behave as it should. Most of these times, problem was of PEBKAC (problem exists between keyboard and chair) type. Computers (nearly) always do, what they're told to do. Under influence of Java Puzzlers book by Neal Gafter and Joshua Bloch, I've decided to start series of posts to this blog, which would cover situations when program doesn't do what we think it should. At first posts will be mostly in C/C++, but i think more languages will be covered in the future. Posts will be formated, so that you'll see only problem with possible answers. Solution will have font color set to background color, or some close color, so you'd have to highlight block in order to see it. You're more than welcome to add your own puzzlers. Just contact me.

Thursday, October 16, 2008

Java Puzzlers

Oh my - oh my - oh my. Yet another funny presentation, this time by Joshua Bloch (Author of Effective Java) and Neal Gafter (Java Puzzlers: Traps, Pitfalls, and Corner Cases, closures proposal for Java7). Presentation is from JavaPolis 2007 and it's called Java Puzzlers/Overview. It's interesting even for non Java programmers.

Tuesday, September 23, 2008

Rules of API design

Joshua Bloch, author of Effective Java writes article about key principles of designing API's. However not only API developers should read this, because as first points states: "All programmers are API designers".
These principles are also mentioned in his original presentation:
How to Design a Good API & Why it Matters.

Wednesday, August 27, 2008

C++ coding style

Ever needed guide for c++ coding style ? Google recently came up with this.

Wednesday, March 5, 2008

Things I hatedon't like about Ruby

Ruby is quite cool, I like lot of features, but for me as C/C++ developer there are some things, which are quite annoying. Please note, that I'm aware that lot of issues I mention here are actually Ruby features. This post will be dynamic, so more items will be eventualy added. For each issue, I'll try to search for solution or workaround. Also I encourage you to post any ideas you might have about solving these problems.

  • multiple classes per file
    I know that you can have more classes in C++ as well, but I like Java way. I also know that Ruby doesn't force you into writing multiple classes per file, but it also doesn't discourage people that write spaghetti code. If you end up maintaining project like this, it's hell.
    Solution: Use search to navigate project, or refactor to class per file.

  • variables doesn't have to be declared
    This is anoying, if you have to study some old code. In Java/C++ world you have to declare class/object variables. If you look at the code after some time you have all members of the class neatly organised at declaration section. In ruby you're free to use variable wherever you like, without first declaring it.
    Solution: correct way of using members is to use accessors: attr_reader, attr_accessor, and attr_writer.
    Well ... one friend had good note: "Always code, as if the guy which end up maintaining your code is violent psychopat, who knows where you live."

  • arguments lack type information
    This is related to previous item. Coding with strongly type-based languages is quite addictive. Switching to Ruby, you'll start missing those: "cannot cast x to y" errors from compiler.
    Solution: ?

Wednesday, February 27, 2008

RDT - IDE for Ruby development

I've been assigned to a project which is developed in Ruby. Because I'm not familliar with Ruby, I decided to use some IDE to work on the project. Because i like Eclipse for java/c++ development, my first choice was to look for Eclipse based IDE. Quick google search returned RDT - or rubyeclipse. Of course I've also bookmarked Ruby Tutorial. I'll post more after I play with it a little bit.