tag:blogger.com,1999:blog-30605163455833042292024-03-08T02:00:53.667-08:00Ben Arciszewski DevelopmentA Blog about developing with Java, Google Web Toolkit (GWT), Android, Scala and other technologies.Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.comBlogger52125tag:blogger.com,1999:blog-3060516345583304229.post-4461647765168249112013-08-27T13:34:00.002-07:002013-08-27T13:34:51.930-07:00Writing Successful Applications, Part IIMy next few posts will be more technical, in the meantime here is another piece I wrote for Noble Applications<br />
<br />
<a href="http://nobleapplications.com/blog/">Part II - How to resolve the UDI</a>Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-86837556299681908722013-08-16T09:15:00.000-07:002013-08-16T09:15:06.886-07:00Writing Successful ApplicationsI've posted another entry to the Noble Applications Blog. I present some thoughts on why software projects often fail and what I think the root cause is. Give it a read, give me some feedback...<br />
<br />
<a href="http://nobleapplications.com/writing-successful-applications/">http://nobleapplications.com/writing-successful-applications/</a><br />
<br />
<br />Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-39778748637546774722013-07-08T13:49:00.001-07:002013-07-08T13:49:42.031-07:00Love AppleI'm now blogging for my new company, <a href="http://www.nobleapplications.com/">Noble Applications</a>. I'll try to post links to my articles for them here so you can stay current.<br />
<br />
<a href="http://nobleapplications.com/love-apple/">I Love Apple</a><br />
<br />
Yes, that is the title of my post. Yes, you should read it to find out why.Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-45726619461707935292013-06-28T16:50:00.001-07:002013-06-28T16:50:03.746-07:00A new positionI don't usually post much on my blog about my work status. Heck, I don't usually post much on my blog. However, I think its prudent to say this announcement is blog worthy, since it should allow me to post much more frequently. <br />
<br />
I've made a very difficult decision to leave my current position at <a href="http://www.studyblue.com/">StudyBlue</a> and take a new one at Noble Applications. Starting Monday I am the new Director of Software Development at <a href="http://www.nobleapplications.com/">Noble Applications</a>. Noble Applications is an application development consultant that specializes in mobile apps. Yes, we do lots of server work too, but our core value proposition is in native Android and iPhone development. I am very excited about this opportunity to expand and grow a development team.Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-17587491099779982302012-12-15T15:50:00.000-08:002012-12-15T15:50:09.845-08:00Scala And Android Were Made For Each Other, Part 2This is the second in a 2 part post. To read the first post, Click Here.<br />
<div>
<br /></div>
<div>
Now that we've gone over the Service in our application, lets review the Activity. Just in case you haven't read part 1, here's a 10 second recap:</div>
<div>
<br /></div>
<div>
We're building a countdown timer for the specific case of tracking a Pomodoro, a 25 minute block of time. For more info, visit the <a href="http://www.pomodorotechnique.com/">Pomodoro Technique</a> site, or maybe, order <a href="http://www.amazon.com/gp/product/1934356506/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1934356506&linkCode=as2&tag=benarcis-20">Pomodoro Technique Illustrated...</a><img alt="" border="0" height="1" src="http://www.assoc-amazon.com/e/ir?t=benarcis-20&l=as2&o=1&a=1934356506" style="border: none !important; margin: 0px !important;" width="1" /><br />
<br />
We've reviewed the Service and seen how the Scala language allows us to reduce a lot of boilerplate code. Now lets look at the Activity:<br />
<br /></div>
<div>
<pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">1: class ScalaDoro extends FragmentActivity with Actionable with MessageReceiver {
2: /** Messenger for communicating with service. */
3: var mService: Messenger = null
4: /** Flag indicating whether we have called bind on the service. */
5: var mIsBound: Boolean = false
6: var running = false
7: override def onCreate(savedInstanceState: Bundle) {
8: super.onCreate(savedInstanceState)
9: setContentView(R.layout.activity_main)
10: spawn {
11: startService(new Intent(ScalaDoro.this, classOf[BackgroundTimer]))
12: }
13: if (savedInstanceState != null) {
14: running = savedInstanceState.getBoolean("running", false)
15: val timerString = savedInstanceState.getString("timerText")
16: getSupportFragmentManager().findFragmentById(R.id.timer).asInstanceOf[CountdownTimerFragment].updateTime(if (timerString != null) timerString else "")
17: }
18: val button = findViewById(R.id.foo_button).asInstanceOf[Button]
19: //awesome lack of boilerplate code...
20: if (!running) {
21: button.setOnClickListener(toOnClickListener(startClickListener))
22: button.setText(R.string.start)
23: } else {
24: button.setOnClickListener(toOnClickListener(stopClickLister))
25: button.setText(R.string.stop)
26: }
27: val donate = findViewById(R.id.donate).asInstanceOf[TextView]
28: if(donate != null) {
29: donate.setText(Html.fromHtml("<a href='https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2RYS72VS6BJAA'>Is this useful to you? Donate via PayPal.</a>"));
30: donate.setMovementMethod(LinkMovementMethod.getInstance());
31: }
32: }
33: override def onSaveInstanceState(bundle: Bundle) = {
34: bundle.putBoolean("running", running)
35: bundle.putString("timerText", getSupportFragmentManager().findFragmentById(R.id.timer).asInstanceOf[CountdownTimerFragment].getTime.toString())
36: }
37: def onMessage(m: Message) = {
38: Log.i("BAA", "Message in Activity")
39: m.what match {
40: case BackgroundTimer.TICK =>
41: val textFragment = getSupportFragmentManager().findFragmentById(R.id.timer).asInstanceOf[CountdownTimerFragment]
42: if (textFragment != null) {
43: runOnUiThread {
44: textFragment.updateTime(m.obj.asInstanceOf[String])
45: }
46: }
47: case BackgroundTimer.STOPPED =>
48: val button = findViewById(R.id.foo_button).asInstanceOf[Button]
49: button.setOnClickListener(toOnClickListener(startClickListener))
50: button.setText(R.string.start)
51: }
52: }
53: def stopClickLister(v: View): Unit = {
54: val button = findViewById(R.id.foo_button).asInstanceOf[Button]
55: try {
56: running = false
57: // Give it some value as an example.
58: Log.i("BAA", "Sent message")
59: button.setOnClickListener(toOnClickListener(startClickListener))
60: val msg = Message.obtain(null, BackgroundTimer.STOP)
61: msg.replyTo = mMessenger
62: mService.send(msg);
63: } catch {
64: case ex: Exception => Log.i("BAA", ex.getMessage())
65: }
66: button.setText(R.string.start)
67: }
68: def startClickListener(v: View): Unit = {
69: val button = findViewById(R.id.foo_button).asInstanceOf[Button]
70: try {
71: // Give it some value as an example.
72: button.setOnClickListener(toOnClickListener(stopClickLister))
73: running = true
74: val msg = Message.obtain(null,
75: BackgroundTimer.START)
76: msg.replyTo = mMessenger
77: mService.send(msg);
78: Log.i("BAA", "Sent message")
79: } catch {
80: case ex: Exception => Log.i("BAA", ex.getMessage())
81: }
82: button.setText(R.string.stop)
83: }
84: //binding code..
85: val mConnection = new ServiceConnection() {
86: override def onServiceConnected(className: ComponentName, service: IBinder) = {
87: Log.i("BAA", "OnServiceConnected called")
88: // This is called when the connection with the service has been
89: // established, giving us the service object we can use to
90: // interact with the service. We are communicating with our
91: // service through an IDL interface, so get a client-side
92: // representation of that from the raw service object.
93: mService = new Messenger(service)
94: // We want to monitor the service for as long as we are
95: // connected to it.
96: try {
97: // Register to receive the notifications
98: val msg = Message.obtain(null,
99: BackgroundTimer.REGISTER)
100: msg.replyTo = mMessenger
101: mService.send(msg)
102: //Now get status
103: val status = Message.obtain(null, BackgroundTimer.STATUS)
104: status.replyTo = mMessenger
105: mService.send(status);
106: Log.i("BAA", "Sent message")
107: } catch {
108: case ex: Exception => Log.i("BAA", ex.getMessage())
109: }
110: mIsBound = true;
111: }
112: def onServiceDisconnected(className: ComponentName) = {
113: // This is called when the connection with the service has been
114: // unexpectedly disconnected -- that is, its process crashed.
115: mService = null;
116: }
117: }
118: override def onStart = {
119: super.onStart()
120: // Bind to the service
121: Log.i("BAA", "Binding")
122: bindService(new Intent(this, classOf[BackgroundTimer]), mConnection, Context.BIND_AUTO_CREATE);
123: }
124: @Override
125: override def onStop = {
126: super.onStop()
127: Log.i("BAA", "Unbinding")
128: // Unbind from the service
129: if (mIsBound) {
130: try {
131: // Give it some value as an example.
132: val msg = Message.obtain(null,
133: BackgroundTimer.UNREGISTER)
134: msg.replyTo = mMessenger
135: mService.send(msg)
136: Log.i("BAA", "Sent message")
137: } catch {
138: case ex: Exception => Log.i("BAA", ex.getMessage())
139: }
140: unbindService(mConnection)
141: mIsBound = false;
142: }
143: }
144: }
</code></pre>
</div>
<div>
<br />
The first thing to notice is that we are using 2 Traits. Actionable and MessageReceiver. You can see, even with this simple app, we're composing functionality from small pieces, and we're reusing code from the Service. I've never NEEDED multiple inheritance, but in this case, it sure is nice. We've already seen MessageReceiver, but lets take a look at Actionable:<br />
<br />
<br /></div>
<div>
<pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">1: package com.example.scaladoro.activity
2: import android.view.View
3: trait Actionable {
4: implicit def toRunnable[F](f: => F): Runnable = new Runnable() { def run() = f }
5: implicit def toOnClickListener(f: View => Unit): View.OnClickListener = new View.OnClickListener() { def onClick(v: View) = f(v) }
6: }
</code></pre>
</div>
<div>
<br />
Actionable simply holds 2 implicit definitions. These allow us to use functions in our Activity instead of having to constantly create new Abstract inner classes. Now when I want to run something on the UI thread, I just use the syntax on line 43. No 'new' keyword, no class definition, no methods to mark @Override. Just the code that will be run. All the cruft that obfuscates what we're trying to do is gone.<br />
<br />
Notice I had to use additional syntax to set the click listeners (line 21). I defined the click listener functions in the activity, and Scala's compiler didn't like them until I wrapped them in the implicit. It doesn't add a ton of code and I find it to be a much cleaner implementation of the state/strategy pattern than creating abstract classes, so I'm willing to live with it.<br />
<br />
Take another look at the code. Once again, there is is very little 'boilerplate' and nice cohesion. Once you understand the Scala syntax, its also a lot easier to read and to reason about what is going on than the equivalent Java code. At least, it is for me. <br />
<br />
If you are interested in seeing the app run, go ahead and download it. I've posted it to the Play store:<br />
<br />
Want to try the app out? <a href="https://play.google.com/store/apps/details?id=com.arciszewski.scaladoro&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS5hcmNpc3pld3NraS5zY2FsYWRvcm8iXQ..">Download Campari Pomodoro</a>.<br />
<br />
<br /></div>
Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-54919696152252816942012-12-08T07:50:00.000-08:002012-12-08T07:50:38.720-08:00Scala And Android Were Made For Each OtherI've been experimenting with Scala for a while now, and the more I use it, the more I like it. Scala isn't exactly what I would call an approachable language, but if you are familiar with Java or C# and you slowly work your way into it, Scala is really a joy to work in. <br />
<div>
<br /></div>
<div>
I also like to write apps for Android. Since Scala runs on the JVM, it runs on Android, too. Recently I've started to think that Google made a mistake using Java for Android. It probably helped Android gain apps and popularity since thousands of developers could install the Eclipse Android Plugin and start coding, but that's the thing - Coding on Android is very different than coding, say, a Web app. It's even quite different than coding a desktop app. And it is because of the way that things should be written on Android that Java seems to be a poor fit. All those thousands of programmers started writing apps - and did it wrong. <br />
<br /></div>
<div>
I know. I made tons of mistakes. As I read more about the platform and become more familiar with how things ran, it is clear that a lot of what I did often wasn't a best practice. Some of what I did was just wrong. <br />
<br /></div>
<div>
This is where I get to the title of this post. I recently experimented and wrote an application for Android using Scala. I have to say, after writing the application this way, I don't ever want to go back. It is my sincere belief that Scala is a much better fit for writing applications on Android than Java. To prove my point, I am going to go through the app I wrote and show you the Scala code. I am going to assume if you are reading this that you already have some familiarity with Android development so I will refrain from showing the Java alternative.<br />
<br />
I'm also going to point out that I am in no way a functional programming expert. As I said, I use Scala as a better Java. My code continues to become 'more functional', but I'm sure this is not idiomatic Scala. That's okay by be, though, because things are just easier. To me, that's the best measure of how good the code is.<br />
<br />
<h3>
Background</h3>
</div>
<div>
We recently had half our staff move to an office in San Francisco. Our company has always moved at a rapid pace, but with the additional overhead of working with a team 2 hours difference and across the US, I was feeling like I was getting distracted. I wanted to find a management technique that was simple and that would help me stay on track. I picked the Pomodoro technique - it was simple. It suited me. It was invented by a programmer, and there were several apps in the Play store for me to use. Of course, I wanted to write my own anyway.</div>
<div>
<br /></div>
<div>
For the purpose of this app, all you need to know is that a Pomodoro is a 25 minute block of time where you concentrate on doing work. Since this is a pretty straight forward app to write, though, I thought I would implement it in Scala to see how it went. <br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://www.amazon.com/gp/product/1934356506/ref=as_li_qf_sp_asin_il?ie=UTF8&camp=1789&creative=9325&creativeASIN=1934356506&linkCode=as2&tag=benarcis-20" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="http://ws.assoc-amazon.com/widgets/q?_encoding=UTF8&ASIN=1934356506&Format=_SL110_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=benarcis-20" /></a></div>
If you want to know more about the Pomodoro Technique, you can visit the official<a href="http://www.pomodorotechnique.com/"> Pomodoro Technique</a> page or Buy the book on Amazon (convenient link on the left).<br />
<div>
<img alt="" border="0" height="1" src="http://www.assoc-amazon.com/e/ir?t=benarcis-20&l=as2&o=1&a=1934356506" style="border: none !important; float: right; margin: 0px !important;" width="1" /></div>
<br />
<br />
<h3>
</h3>
<h3>
<br /></h3>
<h3>
<br /></h3>
<h3>
Application Definition</h3>
</div>
<div>
Here are the things I want the application to do:</div>
<div>
<ul>
<li>Allow me to start a Pomodoro (a 25 minute block of time)</li>
<li>Play the ticker sound while in a Pomodoro (for some reason, hearing this helps me stay on track)</li>
<li>Play a bell when the Pomodoro finishes</li>
<li>Allow me to cancel a Pomodoro if I have to</li>
<li>Keep the Pomodoro timer running, even if I close the application </li>
</ul>
</div>
<div>
Here are the constituent parts of my application:</div>
<div>
<ul>
<li>Activity - Main activity, only Activity. It has the text that shows you the time left and a button that changes states. The button will either start or stop the timer.</li>
<li>Service - A background service that will run the timer task - counting down </li>
</ul>
<div>
If you've done any Android programming in the past, you realize that even these simple requirements will result in a slew of callbacks, threads, anonymous inner classes, binders, messengers...need I go on? Okay, that was a bit of an exaggeration, but not as exaggerated as it seems. <br />
<br />
Let's think about this for a moment. In order to prevent ANR warnings we need to keep things off the main thread, which, means any communication with our service should be run in separate threads. Allowing the service to run separately from the Activity (and allow it to potentially be started and called from any activity, even someone else's) will require it to be started and bound so we'll need a Binder and then we'll need to implement its callbacks. Then communication should happen with Messages so we'll need a Messenger and we'll need to implement its callbacks. Oh, and if we want to update the UI so users know whats going on, we need to then run updates from background threads on the UI thread, which, requires a Runnable.<br />
<br />
When you add all this up, it makes for lots of boilerplate code. Thankfully, the language features of Scala make this less verbose, easier to write, more understandable, and ultimately easier to maintain. It also makes it much easier to write code that will follow Android best practices.</div>
</div>
<div>
<br /></div>
<div>
Now that we know the what and the how, let's talk code. <br />
<br /></div>
<div>
<h3>
The Code</h3>
<div>
<br /></div>
We know we want a bound service that we can send messages to. When you read the<a href="http://developer.android.com/guide/components/bound-services.html"> Android docs</a> on it, you'll see that there is a abstract inner class that implements Handler and is passed to a Messenger that is returned in the Services onBind method.</div>
<div>
<br />
Wow, that was a lot to say. It is also a lot of boilerplate code. I wanted to move this to a common class so it was out of my way. In Java we might make an Abstract base class. But wait, the Activity in our application also needs a Handler and a Messenger, and if we Make an AbstractService, we could not use that code in an Activity. If we make an AbstractActivity, we cannot use it for our Service. Here is the first place where Scala is quite handy. I was able to make a <a href="http://www.scala-lang.org/node/126">Trait</a>. Traits are very powerful and I'm using the one below as a 'better interface', which, might be under-utilizing this great feature. It serves its purpose well, however.</div>
<div>
<br /></div>
<pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">1: trait MessageReceiver {
2: implicit def toIncomingHandler(f: Message => Unit): Handler = new Handler() { override def handleMessage(message: Message) = f(message) }
3:
4: val mMessenger = new Messenger({ m: Message =>
5: onMessage(m)
6: })
7:
8: def onMessage(m: Message)
9: }
</code></pre>
<div>
<br />
Notice that I also used an implicit to reduce the need to declare an abstract inner class to handle the message. I probably didn't save any code, but I like the way this looks far better than the Java alternative.<br />
<br />
Now that we have the MessageReceiver defined, let's define our Service. Before I show you the code, here are some things I want you to notice about the class:<br />
<br />
<ul>
<li>We override onMessage and implement it. This is the only code in this class that is related to receiving a message. All the boilerplate has been moved to the Trait which can be used by both Activity and Service classes.</li>
<li>The start method has an internal method called timer that is recursive. This also happens to be tail recursive, and Scala is smart enough to unwind this, so it won't grow my stack. </li>
<li>We run the timer in a background thread. Notice that all we have to do is surround it with a spawn{} block. (I omitted the imports, but you need to import scala.concurrent.ops._ to do this)</li>
</ul>
<br />
<br /></div>
<pre style="background-image: URL(http://2.bp.blogspot.com/_z5ltvMQPaa8/SjJXr_U2YBI/AAAAAAAAAAM/46OqEP32CJ8/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">1: case class BackgroundTimer extends Service with MessageReceiver {
2:
3: var millis = 0L;
4: /** Keeps track of all current registered clients. */
5: var mClients = List[Messenger]()
6: var currentTime = "0:00"
7:
8: val mediaPlayer = new SoundPool(2, AudioManager.STREAM_MUSIC, 0)
9:
10: var tickId: Int = -1
11: var alarmId: Int = -1
12: var tickStreamId = -1
13:
14: override def onMessage(m:Message) = {
15: m.what match {
16: case BackgroundTimer.REGISTER =>
18: mClients ::= m.replyTo
19: }
20: case BackgroundTimer.UNREGISTER =>
21: if (m.replyTo != null) {
22: mClients = mClients.remove(messenger =>
23: if (messenger == m.replyTo) {
24: true
25: } else {
26: false
27: })
28: }
29: case BackgroundTimer.START >
30: start()
31: case BackgroundTimer.STOP =>
32: //don't play the alarm bell
33: stop(true)
34: }
35: }
36:
37: override def onStartCommand(intent: Intent, flags: Int, startId: Int): Int = {
38: Log.i("BAA", "Received start id " + startId + ": " + intent)
39: try {
40: tickId = mediaPlayer.load(this, R.raw.singletick, 1)
41: alarmId = mediaPlayer.load(this, R.raw.alarm, 1)
42: } catch {
43: case e: Exception => Log.d("BAA", e.getMessage())
44: }
45: Service.START_STICKY; // run until explicitly stopped.
46: }
47:
48: /**
49: * Must override this to allow the service to bind to the Activity so we can start/stop timers
50: */
51: override def onBind(intent: Intent): IBinder = {
52: Log.i("BAA", "OnBind called")
53: return mMessenger.getBinder()
54: }
55:
56: def start() = {
57: if (millis == 0) {
58: spawn {
59:
60: var alarmStreamId = -1
61: try {
62: tickStreamId = mediaPlayer.play(tickId, 2.0f, 2.0f, 1, -1, 1.0f)
63: } catch {
64: case e: Exception => Log.d("BAA", e.getMessage())
65: }
66:
67: def timer(millisLeft: Long): Unit = {
68: if (millis > 0) {
69: millis = millisLeft
70: }
71: val seconds = (millisLeft / 1000) % 60;
72: val minutes = ((millisLeft / (1000 * 60)) % 60);
73: currentTime = minutes + ":" + (if (seconds > 9) seconds else "0" + seconds)
74:
75: if (millis > 0) {
76: mClients.foreach { messenger =>
77: val response = Message.obtain(null, BackgroundTimer.TICK, 0, 0, currentTime)
78: messenger.send(response)
79: }
80: Thread.sleep(995);
81: timer(millisLeft - 995)
82: } else {
83: stop(false)
84:
85: }
86: }
87: //now start it off...
88: millis = 1000 * 60 * 25
89: timer(millis)
90: }
91: }
92: }
93:
94: def stop(forced:Boolean) = {
95: millis = 0
96: currentTime = "0:00"
97: mediaPlayer.stop(tickStreamId)
98: if(!forced)
99: mediaPlayer.play(alarmId, 0.2f, 0.2f, 1, 0, 1.0f)
100: mClients.foreach { messenger =>
101: val response = Message.obtain(null, BackgroundTimer.STOPPED, 0, 0, currentTime)
102: messenger.send(response)
103: }
104: }
105: }
106:
107: /**
108: * Define an object to hold some statics
109: */
110: object BackgroundTimer {
111: val REGISTER = 1
112: val START = 2
113: val STOP = 3
114: val UNREGISTER = 4
115: val STARTED = 5
116: val STOPPED = 6
117: val TICK = 7
118: }
119:
</code></pre>
<div>
<br />
I don't know about you, but this class looks very clean to me. Almost all the code is directly related to what this class is intended to do with no messy boilerplate code for messaging or threading. In fact, threading is now too easy - just add a spawn block and done. The 'business logic' is also very compact. Since timer can be declared inside start, all the logic for actually running the timer is in one spot - no need to jump to a different section of code to see what's going on. <br />
<br />
Want to try the app out? <a href="https://play.google.com/store/apps/details?id=com.arciszewski.scaladoro&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS5hcmNpc3pld3NraS5zY2FsYWRvcm8iXQ..">Download Campari Pomodoro</a>.<br />
<br />
Next up, the Activity</div>
Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-81149291898219326182012-08-25T18:07:00.001-07:002012-11-05T08:47:20.578-08:00Learn C Chapter 22 FlashcardsI'm currently slowly going through Zed Shaw's "<a href="http://c.learncodethehardway.org/book/">Learn C The Hard Way</a>". In chapter 22, he instructs you to make flashcards of the C data types and flow control structures. Seeing as how C syntax is really close in many ways to Java syntax, a lot of this stuff is pretty natural. There are several functions, macros and types, though, that are different and that I really should memorize.<br />
<br />
As I just happen to work for a company that writes flashcard apps (<a href="http://studyblue.com/">StudyBlue.com</a>), I figured I might as well create them on the site and share them for anyone else working through the book. So, here are my, <a href="http://s.tudy.it/twmslgc">Learn C The Hard way - Ch 22 - data types and flow control</a> in C flashcards.<br />
<br />
Enjoy.<br />
<br />
<br />Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-6964944542067288732012-07-18T08:00:00.000-07:002012-07-18T08:00:07.548-07:00First TMX Map rendered with TMX-S-ParserWell, I've been working in my infinite spare time on a parser that will allow you to easily use Scala to render maps in the TMX Map format. The project started as a way for me to learn some more about Git and get more experience using Scala. While the Euler problems were nice, I really wanted to do something non-trivial and non-academic in Scala. <br />
<br />
This weekend I was finally able to make some headway on the project again and I was able to get my sample map rendered using Swing. Here are the pictures:<br />
<br />
<div style="text-align: center;">
Map as rendered by TMX-S-Parser in Swing</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-Q77t2myQhlk/UAMMGU0Q99I/AAAAAAAAAk4/oW0p3ezFzy8/s1600/scala_tmx_tiled_map.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="212" src="http://1.bp.blogspot.com/-Q77t2myQhlk/UAMMGU0Q99I/AAAAAAAAAk4/oW0p3ezFzy8/s320/scala_tmx_tiled_map.png" width="320" /></a></div>
<br />
<div style="text-align: center;">
Map as rendered in Tiled (Objects hidden)</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-8VNTfXPxyEk/UAMMIkMDSmI/AAAAAAAAAlA/8nLOY-YeM0Y/s1600/tiled_map.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="203" src="http://4.bp.blogspot.com/-8VNTfXPxyEk/UAMMIkMDSmI/AAAAAAAAAlA/8nLOY-YeM0Y/s320/tiled_map.png" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
As you can see, the basic layer rendering seems to be working now. I'm actually quite excited to start working on the other elements that can be in the map - objects, polygons and the like. I also have some ideas for 'properties'. If you'd like to see the code, check out the <a href="https://github.com/barciszewski/TMX-S-Parser">TMX-S-Parser</a> project on Github.</div>
<br />Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-29757356692962187562012-07-14T10:35:00.000-07:002012-07-14T10:35:16.011-07:00Parsing TMX Maps using ScalaA co-worker and friend of mine was recently talking about how he wanted to make games on a phone. He's a fan of turn-based style board games. He was lamenting, though, at how much work it would take just to create things like maps and backgrounds, let alone characters and the like. Of course, there are tools emerging to aid in the building of these things. One of them is <a href="http://www.mapeditor.org/">Tiled</a>. Tiled allows you to create maps from tile set image and store the resulting map definition in an XML file. This format is called <a href="https://github.com/bjorn/tiled/wiki/TMX-Map-Format">TMX Map Format</a>. <br />
<br />
I've recently been playing around with some Scala, and I figured since I liked Scala's XML support so much, I would create a little library that would parse a TMX file, represent the elements as Objects and allow you pretty easily render a Tiled map. <br />
<br />
Who knows, maybe I will eventually turn it into a full-fledged Game framework. For now, though, I'm concentrating on just the TMX parsing and utilities to allow you get the map info into your program. <br />
<br />
<b>The XML. </b><br />
<br />
Since Scala's XML parsing is first-class, it was pretty easy to get started. As I started looking through the <a href="https://github.com/bjorn/tiled/wiki/TMX-Map-Format">documentation</a> and writing tests, a few interesting portions of the code started to pop up. First, it appears that there are several ways to express the ids of the tiles (each ID representing a 'tile' in the image it references). The formats are: XML, csv, and Base64. <br />
<br />
In addition to the different formats, the Base64 data could optionally be compressed using gzip or glib. This presented me with the most interesting portions of the code. First, the XML parser needed to be smart enough to create the Layers correctly depending on the formats. Second, I needed to do some data manipulation to interpret the Base64 data the correct way. <br />
<br />
Let's talk about the XML parsing depending on the different tags. As it turns out, there was very little code for me to write to parse the XML, even with the variable data format. What's interesting, is that I was able to make the parser return an immutable map object, creating each element and all sub-elements while constructing the hierarchy. This is in keeping with my 'least mutable state' exercises I've been working on. Here is a sample of the parsing code:<br />
<br />
<br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"></span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;">def loadMap(src: InputStream): TmxMap = {</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> val xml = XML.load(src)</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> new TmxMap((xml \ VERSION).text,</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> (xml \ ORIENTATION).text,</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> (xml \ WIDTH).text.toInt,</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> (xml \ HEIGHT).text.toInt,</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> (xml \ TILE_WIDTH).text.toInt,</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> (xml \ TILE_HEIGHT).text.toInt,</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> xml \ TILE_SET collect { case tileSet: Node => new TmxTileset((tileSet \ FIRST_GID).text, (tileSet \ NAME).text, getValue((tileSet \ TILE_WIDTH).text), getValue((tileSet \ TILE_HEIGHT).text), createImage((tileSet \ IMAGE).first)) },</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> xml \ LAYER collect {</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> case layer: Node =></span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"><br /></span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> if (!(layer \ DATA \ ENCODING).text.isEmpty()) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"><br /></span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> TmxLayer.fromData((layer \ NAME).text, getValue((layer \ WIDTH).text), getValue((layer \ HEIGHT).text), (layer \ DATA \ ENCODING).text, (layer \ DATA \ COMPRESSION).text, (layer \ DATA).text);</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> } else {</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> TmxLayer.fromTiles((layer \ NAME).text, getValue((layer \ WIDTH).text), getValue((layer \ HEIGHT).text),</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> layer \ DATA \ TILE collect { case tile: Node => new TmxTile(getValue((tile \ GID).text)) })</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> },</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> xml \ OBJECT_GROUP collect {</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> case objectGroup: Node => new TmxObjectGroup((objectGroup \ NAME).text, getValue((objectGroup \ WIDTH).text), getValue((objectGroup \ HEIGHT).text),</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> objectGroup \ OBJECT collect {</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> case obj: Node => new TmxObject((obj \ NAME).text, getValue((obj \ X).text), getValue((obj \ Y).text), getValue((obj \ GID).text),</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> obj \ POLYGON collect { case poly: Node => new PropertiesFactory[TmxPolygon].setProperties(poly \ PROPERTIES, new TmxPolygon(parsePoints((poly \ POINTS).text))) })</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> })</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> })</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: xx-small;"> }</span><br />
<br />
<br />
<br />
What should pop out at you right away is that the loadMap function essentially has two statements. One loads the XML, the other creates a new TmxMap. There is a LOT going on here and I often consider breaking this up a little into smaller methods so its more readable and digestible, but its interesting to see how you can create compound statements in Scala.<br />
<br />
<span style="background-color: white;">The next most interesting thing is that if the data comes across as Base64, it is supposed to be interpreted as a byte array of unsigned little-endian integers.</span><br />
<br />
Well, Java and Scala do not have unsigned types, so this required a little bit of conversion. Interestingly, my first attempt used Sun's undocumented decoder. I ran into an interesting issue with it. It did not remove the carriage returns from my XML data before passing it to the decoder. The decoder returned values, but they were wrong. I re-implemented the function using the Apache Commons decoder, and it works just fine. This leads me to wonder, though. Which is more correct? Should I remove all carriage returns from my data before parsing or should a decoder be able to recognize that? I'm not sure which I would prefer. <br />
<br />
I've created a project for this called, <a href="https://github.com/barciszewski/TMX-S-Parser">TMX-S-Parser</a> on github and I intend to keep adding to it until I'm satisfied it is robust and complete. Take a look at the code. If you have the will, copy the repo, make some changes, recommend improvements, add utility.Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-15465977705529960012012-01-19T14:05:00.000-08:002012-01-19T14:05:39.709-08:00Project Euler Problem 10 in Scala<span style="font-family: Arial, Helvetica, sans-serif;">This is 10 in a series. The previous post is at, <a href="http://benarchie.blogspot.com/2012/01/project-euler-problem-9-in-scala.html">Project Euler Problem 9 in Scala</a>. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">Problem 10 on project Euler is:</span><br />
<br />
<blockquote class="tr_bq">
<span style="font-family: Arial, Helvetica, sans-serif;">The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.<br />Find the sum of all the primes below two million.</span></blockquote>
<br />
<span style="font-family: Arial, Helvetica, sans-serif;">Problem 10 posed an interesting issue for me. I came up with a solution I thought would work well right away, but I couldn't seem to get the correct answer. After poring over my code and playing around, I finally found my issue - my isPrime function had an error in it, causing me to be off by 2. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">What is interesting about this scenario is that I've been using that same function for lots of different problems, but since the function was only broken for the number 2, it didn't matter in those. If I had some sort of test that say, verified the function against a random set of prime numbers, I would have found the issue much sooner. This speaks to how important it is to test even seemingly working things whenever you can. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">Another by product of the issue is that I did a little more research on calculating prime numbers. Wikipedia had a nice article about the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes</a>. This gave me a much better understanding of how it works. While I am not changing my code (yet) to use a sieve, it was certainly valuable to learn more about how its done. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">Well, I did manage to finish it, and here is my solution. Enjoy:</span><br />
<br />
<br />
<span style="font-family: 'Courier New', Courier, monospace;">object Problem10 {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> def main(args: Array[String]): Unit = {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> var holder : BigDecimal = new BigDecimal(new java.math.BigDecimal("0"));</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> (2 to 1999999).filter{next => val prime = isPrime(next);if(prime){holder = holder + new java.math.BigDecimal(new Integer(next).toString())};prime}</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> println(holder)</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> /**</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> * Brute force method. Perhaps a better method </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> * can be implemented here? </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> */</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> def isPrime(number: Long) : Boolean = {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> if(number == 2)</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> return true</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> if(number%2==0 || number % 3==0)</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> return false;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> val sqrt:Int = Math ceil (Math sqrt number) intValue;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> (true /: (3 to sqrt))((isPrime, next) => {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> if(number % next == 0) </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> return false </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> isPrime</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> })</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;">}</span><br />
<br />
<br />
<span style="font-family: Arial, Helvetica, sans-serif;">Now that I've completed #10, I get a Euler award. I have become a 'Decathlete' for finishing 10 problems in a row. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">And with that, I think I will finish blogging about my Euler solutions. I still plan on working through the problems, but I think I've worn out my Euler solution posts and will move on to some other interesting topics. </span><br />
<br />Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com1tag:blogger.com,1999:blog-3060516345583304229.post-16260525571595841572012-01-14T08:40:00.000-08:002012-01-14T08:40:23.360-08:00StudyBlue Flashcards nominated for Best App Ever Awards<span style="font-family: Arial, Helvetica, sans-serif;">I've been working for <a href="http://www.studyblue.com/">StudybBlue</a> for about 9 months now. If you don't know what StudyBlue is, it's a fantastic place for students to create online flashcards, study those flashcards, create quizzes from them, and track their progress. In other words, its a product that makes students more efficient and effective. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><a href="http://www.studyblue.com/">StudyBlue</a> is more than a Web site, however. It also produces native flashcard applications for <a href="http://itunes.apple.com/ie/app/studyblue/id323887414">iPhone</a> and <a href="https://market.android.com/details?id=com.studyblue&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS5zdHVkeWJsdWUiXQ..">Android</a> to allow students to study their cards on the go. The goal for our company is to create a total user experience and we invest a lot of time, effort and energy into our application designs. Apparently, that hard work is starting to payoff. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">We were recently notified that we were nominated for the the <a href="http://www.bestappever.com/v/hsed/2/com.studyblue/vote">Best App Ever Awards</a>. While its not the biggest award or the best known, the interesting thing about it is that it is a user-driven award. It means that one of our users nominated our app and other users will be voting on it. In my mind this is one of the highest compliments <a href="http://www.studyblue.com/">StudyBlue</a> could be paid. After all, it doesn't really matter what anyone thinks but your users, and it seems that we're keeping at least some of ours pretty happy. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">If you are a student and use </span><a href="http://www.studyblue.com/" style="font-family: Arial, Helvetica, sans-serif;">StudyBlue</a><span style="font-family: Arial, Helvetica, sans-serif;">, please </span><a href="http://www.bestappever.com/v/hsed/2/com.studyblue/vote" style="font-family: Arial, Helvetica, sans-serif;">vote</a><span style="font-family: Arial, Helvetica, sans-serif;"> for our app. There would be nothing more satisfying than knowing that our users think we're the Best App Ever.</span>
<br />
<a class="bae-nominate-btt" href="http://www.bestappever.com/v/hsed/2/com.studyblue" style="text-align: center;">Vote for STUDYBLUE Flashcards for Best High School Student App</a><link href="http://www.bestappever.com/template/2011/vote-button.css" media="screen" rel="stylesheet"></link>Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-55908518145038494272012-01-14T07:58:00.000-08:002012-01-14T07:58:54.264-08:00Project Euler Problem 9 in Scala<span style="font-family: Arial, Helvetica, sans-serif;">This is 9 in a series. The previous post is at, <a href="http://benarchie.blogspot.com/2012/01/project-euler-problem-8-in-scala.html">Project Euler Problem 8 in Scala</a>. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">I've still been (slowly) working my way through the Project Euler Problems. The next one is problem 9 which reads:</span><br />
<blockquote class="tr_bq">
<span style="font-family: Arial, Helvetica, sans-serif;">A Pythagorean triplet is a set of three natural numbers, a b c, for which,<br />a^2 + b^2 = c^2<br />For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.<br />There exists exactly one Pythagorean triplet for which a + b + c = 1000.<span class="Apple-tab-span" style="white-space: pre;"> </span>Find the product abc.</span></blockquote>
<span style="font-family: Arial, Helvetica, sans-serif;">For this problem, I didn't use anything fancy. Two for-comprehensions and basic math produced the solution in short order. The only thing to mention about this solution is that it actually finds the solution twice since I'm iterating1 to 998 twice. I considered trying to optimize this, however, it runs plenty fast. Since my goal in solving these isn't to come up with the fastest solution, but to come up with a solution that has no mutable state, I have met my goal. Therefore, I present you the solution to problem 9:</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<br />
<span style="font-family: 'Courier New', Courier, monospace;">object Problem9 {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> def main(args: Array[String]): Unit = {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> for (a <- 1 to 998) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> for (b <- 1 to 998) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> val c = 1000 - (a + b)</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> if ((a * a) + (b * b) == (c * c)) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> println("the triplet is " + a + " " + b + " " + c)</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> println("the product is " + (a * b * c))</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;">}</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">I think that's all for this one. Problem 10 is in the hopper...</span><br />
<br />Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-18284025809935477212012-01-09T07:00:00.000-08:002012-01-09T07:00:09.600-08:00Project Euler Problem 8 in Scala<span style="font-family: Arial, Helvetica, sans-serif;"><span style="background-color: white; color: #333333; line-height: 16px; text-align: left;">This is 8 in a series. The previous post is at, </span><a href="http://benarchie.blogspot.com/2011/12/project-euler-problem-7-in-scala.html" style="background-color: white; color: #336699; line-height: 16px; text-align: left;">Project Euler Problem 5 in Scala</a><span style="background-color: white; color: #333333; line-height: 16px; text-align: left;">.</span><span style="background-color: white; color: #333333; line-height: 16px; text-align: left;"> </span>
</span><br />
<span style="background-color: white; color: #333333; font-family: Arial, Helvetica, sans-serif; line-height: 16px; text-align: left;"><br /></span><br />
<span style="background-color: white; color: #333333; font-family: Arial, Helvetica, sans-serif; line-height: 16px; text-align: left;">So we saw problem 6 solved with a 'one-liner'. Then we moved on to problem 7 and I had to have a while loop and control variables, which really disappointed me. Problem 8, however, was not only satisfying, but allowed me to explore even more features of Scala. </span><br />
<span style="background-color: white; color: #333333; font-family: Arial, Helvetica, sans-serif; line-height: 16px; text-align: left;"><br /></span><br />
<span style="background-color: white; color: #333333; font-family: Arial, Helvetica, sans-serif; line-height: 16px; text-align: left;">Before I get into the actual problem, I want to comment on my language progress. My 'native tongue' so-to-speak, is Java. I use Java at work and have for 12 years. I expect it will be paying the bills for years to come. We can debate the merits of Java as a language, and I'm sure every one reading this has an opinion about it, good or bad. Regardless of opinion, I am most productive in Java. Period. Why? Because I have used it so much, and am so familiar with the syntax and libraries that the language 'gets out of the way'. I don't have to think about anything but what the code is intending to do. This makes me very productive. I'm finding that its taking a little longer to get to the point where I feel like the language has stepped back with Scala. Part of it is the rather verbose API documentation, which, just seems to tell me too much and doesn't allow me to get right to 'how do I use this'. Part of it is that Scala has a lot more power and expressiveness than Java, and that takes more time to learn. At any rate, my Scala skills are slowing improving. </span><br />
<span style="background-color: white; color: #333333; font-family: Arial, Helvetica, sans-serif; line-height: 16px; text-align: left;"><br /></span><br />
<span style="background-color: white; color: #333333; font-family: Arial, Helvetica, sans-serif; line-height: 16px; text-align: left;">Now, on to Problem 8:</span><br />
<span style="background-color: white; text-align: left;"><span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"></span></span><br />
<blockquote style="line-height: 16px;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;">Find the greatest product of five consecutive digits in the 1000-digit number.</span></blockquote>
<blockquote style="line-height: 16px;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"> 73167176531330624919225119674426574742355349194934<br /> 96983520312774506326239578318016984801869478851843<br /> 85861560789112949495459501737958331952853208805511<br /> 12540698747158523863050715693290963295227443043557<br /> 66896648950445244523161731856403098711121722383113<br /> 62229893423380308135336276614282806444486645238749<br /> 30358907296290491560440772390713810515859307960866<br /> 70172427121883998797908792274921901699720888093776<br /> 65727333001053367881220235421809751254540594752243<br /> 52584907711670556013604839586446706324415722155397<br /> 53697817977846174064955149290862569321978468622482<br /> 83972241375657056057490261407972968652414535100474<br /> 82166370484403199890008895243450658541227588666881<br /> 16427171479924442928230863465674813919123162824586<br /> 17866458359124566529476545682848912883142607690042<br /> 24219022671055626321111109370544217506941658960408<br /> 07198403850962455444362981230987879927244284909188<br /> 84580156166097919133875499200524063689912560717606<br /> 05886116467109405077541002256983155200055935729725<br /> 71636269561882670428252483600823257530420752963450</span></blockquote>
<div style="line-height: 16px;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"> This problem is pretty straight forward. Iterate the string literal and multiply sets of 5 numbers together. Find the largest of those numbers and return it. Now, in Java, this would take a couple of for loops, a String, possibly a string buffer, some variables to store the results, and an ugly System.out.println....</span></div>
<div style="line-height: 16px;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><br /></span></div>
<div style="line-height: 16px;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;">Not so in Scala. The Collections facilities actually allowed me to solve this in one line, without any mutable state. No, really, I mean it. Check this out:</span></div>
<div style="line-height: 16px;">
<span style="color: #333333; font-size: x-small;"><br /></span></div>
<br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;">object Problem8 {</span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> def main(args: Array[String]): Unit = {</span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> val totalDigits = """[omitted the big string literal here, but you can add it back if you want to run the code...]"""</span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> println((for (i <- 5 to totalDigits.length()) yield totalDigits slice (i - 5, i)) collect {</span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> case i =></span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> i.foldLeft(1)((product: Int, nextChar) => {</span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> (nextChar asDigit) * product</span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> })</span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> } max)</span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> }</span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;">}</span></span></span><br />
<span style="color: #333333; font-size: x-small;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"><br /></span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: Arial, Helvetica, sans-serif;">Okay, its a 'one-liner' but there is a lot going on there. Let's deconstruct the statement. First, we see that everything is wrapped in a 'println', which is nice shorthand in Scala for System.out.println. The second thing we see is that the result of the statement 'max' is what will be printed. max is a collection function. A couple of things to note. Since max takes no arguments, we drop the '()'. Since Scala can infer its a method call, we can even omit the '.'. Now let's look at the rest of the code, shall we?</span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: Arial, Helvetica, sans-serif;"><br /></span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: Arial, Helvetica, sans-serif;">Let's go back to the beginning of the statement. We are using the 'for' comprehension. To be honest, the 'for' comprehension in Scala is much more powerful than the 'for' loop in other languages I've used. You can see, we are going to iterate 5 to the length of the string. For each iteration, we are going to yield the slice if i-5 and i. slice is a nice string operator in Scala. Essentially, we're getting 5 characters. In turn we are going to collect the results of folding (There's that foldLeft again....) the 5 character Sequence. The result of all of these will be a Sequence of Int values, on which we call 'max' function.</span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: Arial, Helvetica, sans-serif;"><br /></span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: Arial, Helvetica, sans-serif;">Boy, that was a mouthful. It was cool, though, wasn't it? It took a few minutes for me to weed through the API and figure out the syntax for this, but in the end, it is a succinct and stateless solution....</span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: Arial, Helvetica, sans-serif;"><br /></span></span></span><br />
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: Arial, Helvetica, sans-serif;">On to the next one...</span></span></span><br />
<span style="color: #333333; font-size: x-small;"><span style="font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;"><br /></span></span></span><br />
<br />Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com2tag:blogger.com,1999:blog-3060516345583304229.post-1601290801778864222012-01-05T07:00:00.000-08:002012-01-07T13:21:48.466-08:00Project Euler Problem 7 in Scala<span style="font-family: Arial, Helvetica, sans-serif;"><span style="background-color: white; color: #333333; line-height: 16px; text-align: left;">This is 7 in a series. The previous post is at, </span><a href="http://benarchie.blogspot.com/2011/12/project-euler-problem-6-in-scala.html" style="background-color: white; color: #336699; line-height: 16px; text-align: left;">Project Euler Problem 6 in Scala</a><span style="background-color: white; color: #333333; line-height: 16px; text-align: left;">.</span></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="background-color: white; color: #333333; line-height: 16px; text-align: left;"><br /></span></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="background-color: white; color: #333333; line-height: 16px; text-align: left;">After a very successful solution to problem 6, we get to problem 7. I couldn't figure out how to remove all mutable state from this solution. The issue is that we have to find the 10,001st number which means that we do not know how long we have to iterate. I used a while loop here, and it seems to work fine. Perhaps someone has a solution without a while loop? </span></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="background-color: white; color: #333333; line-height: 16px; text-align: left;"><br /></span></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="background-color: white; color: #333333; line-height: 16px; text-align: left;">Here's Project Euler problem 7:</span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"></span><br />
<blockquote class="tr_bq" style="line-height: 16px;">
<span style="background-color: white; color: #333333; text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif;"> By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.<br /> <span style="background-color: white;">What is the 10,001st prime number?</span></span></span></blockquote>
<br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;">object Problem7 {</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"><br /></span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> def main(args: Array[String]): Unit = {</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>var counter = 1L;</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>var number = new BigDecimal(new java.math.BigDecimal("0"));</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>var currentNum = 1l;</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span class="Apple-tab-span" style="line-height: 16px; white-space: pre;"><span style="font-family: 'Courier New', Courier, monospace;"> </span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>while(counter <= 10001) {</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> if(isPrime(currentNum)) {</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> number = new BigDecimal(new java.math.BigDecimal(currentNum));</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> counter = counter + 1;</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> }</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> currentNum = currentNum + 1;</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>}</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>println("10001st prime " + number);</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> }</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> </span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> /**</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> * Brute force method. Perhaps a better method </span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> * can be implemented here? </span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> */</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> def isPrime(number: Long) : Boolean = {</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> if(number%2==0)</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> return false;</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> val sqrt:Int = Math ceil (Math sqrt number) intValue;</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> (true /: (3 to sqrt))((isPrime, next) => {</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> if(number % next == 0) </span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> return false </span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> isPrime</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> })</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="line-height: 16px;"><span style="font-family: 'Courier New', Courier, monospace;"> }</span></span></span><br />
<span style="background-color: white; color: #333333; text-align: left;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="background-color: white; line-height: 16px;">}</span><span style="line-height: 16px;"> </span></span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"><span style="line-height: 16px;"><br /></span></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;">You should note that I've cleaned up my isPrime method. I noticed that it wasn't very functionally written, so I changed it to use a fold left (By the way, foldLeft is turning out to be one of the handiest Scala constructs on the planet.) I am now very comfortable with the isPrime method, at least as a brute force solution.</span></span></span>Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-49359935609546717122011-12-31T13:26:00.000-08:002012-01-07T13:22:02.580-08:00Project Euler Problem 6 in Scala<span style="font-family: Arial, Helvetica, sans-serif;"><span style="background-color: white; color: #333333; line-height: 16px; text-align: left;">This is 6 in a series. The previous post is at, </span><a href="http://benarchie.blogspot.com/2011/12/project-euler-problem-5-in-scala.html" style="background-color: white; color: #336699; line-height: 16px; text-align: left;">Project Euler Problem 5 in Scala</a><span style="background-color: white; color: #333333; line-height: 16px; text-align: left;">.</span>
</span><br />
<span style="background-color: white; color: #333333; font-family: Arial, Helvetica, sans-serif; line-height: 16px; text-align: left;"><br /></span><br />
<div style="text-align: left;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;">Problem 6 was particularly satisfying for me. You will see why when you see the code below. I think the code deserves some discussion because it takes advantage of some pretty nice Scala features.</span></span></div>
<div style="text-align: left;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;"><br /></span></span></div>
<div style="text-align: left;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;">Project Euler problem 6 reads:</span></span></div>
<blockquote class="tr_bq">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;">The sum of the squares of the first ten natural numbers is,</span></span><span style="color: #333333; font-family: Arial, Helvetica, sans-serif; line-height: 16px;"> 12 + 22 + ... + 102 = 385</span><span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;">The square of the sum of the first ten natural numbers is, </span></span><span style="color: #333333; font-family: Arial, Helvetica, sans-serif; line-height: 16px;">(1 + 2 + ... + 10)2 = 552 = 3025</span><span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;">Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025-385 = 2640.</span></span><span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;"> </span></span><span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;">Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.</span></span></blockquote>
<div style="text-align: left;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;">So reading this question, we want to come up with an algorithm that iterates all the numbers 1..100. During each iteration, we want to capture the sum of the squares, and the sum of the number. Finally, we want to square the sum of the number and subtract the two values. </span></span></div>
<div style="text-align: left;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;"><br /></span></span></div>
<div style="text-align: left;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;">Using some of Scala's syntactic sugar and its excellent functional handling we get:</span></span></div>
<div style="text-align: left;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: x-small;"><span style="line-height: 16px;"><br /></span></span></div>
<div style="text-align: left;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: x-small;"><span style="line-height: 16px;"><br /></span></span></div>
<div style="text-align: left;">
<span style="color: #333333; font-size: x-small;"><span style="line-height: 16px;"></span></span></div>
<div style="font-family: 'Courier New', Courier, monospace;">
<span style="color: #333333;">object Problem6 {</span></div>
<div style="font-family: 'Courier New', Courier, monospace;">
<span style="color: #333333;"> def main(args: Array[String]): Unit = {</span></div>
<div style="font-family: 'Courier New', Courier, monospace;">
<span style="color: #333333;"> val results = ((0, 0) /: (1 to 100))((i, s) => {</span></div>
<div style="font-family: 'Courier New', Courier, monospace;">
<span style="color: #333333;"> (i._1 + (s * s), i._2 + s)</span></div>
<div style="font-family: 'Courier New', Courier, monospace;">
<span style="color: #333333;"> })</span></div>
<div style="font-family: 'Courier New', Courier, monospace;">
<span style="color: #333333;"> println((results._2 * results._2) - results._1);</span></div>
<div style="font-family: 'Courier New', Courier, monospace;">
<span style="color: #333333;"> }</span></div>
<div style="font-family: 'Courier New', Courier, monospace;">
<span style="color: #333333;">}</span></div>
<div style="font-family: 'Courier New', Courier, monospace;">
<span style="color: #333333; font-size: x-small;"><br /></span></div>
<span style="color: #333333;"><span style="font-family: Arial, Helvetica, sans-serif;">If we take out the object definition and main method call, you can see that this is a two-liner (I could make it a one-liner, but I think that would sacrifice readability). Once again, I am using the foldeLeft operator (/:). This time, however, I am folding left on a sequence of values instead of a single value. Because of this, you see the (0,0) declaration. Scala also infers this type inside the body of the function, so I am storing to values i._1 and i._2. Finally, we square the sums and subtract the sum of the squares.</span></span><br />
<span style="color: #333333;"><span style="font-family: Arial, Helvetica, sans-serif;"><br /></span></span><br />
<span style="color: #333333;"><span style="font-family: Arial, Helvetica, sans-serif;">Note that I actually multiplied results._2 by itself. the '^' operator in Scala seems to work differently than I expected, and was giving me weird results. I might have to look into that, but for now, we have a very succinct solution to this problem. </span></span>Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-8007377611174388572011-12-27T08:04:00.000-08:002012-01-07T13:24:52.853-08:00Project Euler Problem 5 in Scala<span style="background-color: white; color: #333333; line-height: 16px; text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif;">This is 4 in a series. The previous post is at, <a href="http://benarchie.blogspot.com/2011/12/project-euler-problem-4-in-scala.html">Project Euler Problem 4 in Scala</a>.</span></span><br />
<span style="background-color: white; color: #333333; line-height: 16px; text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif;"><br /></span></span><br />
<div style="text-align: left;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;">Here we are, arriving at problem 5 from the </span><a href="http://projecteuler.net/" style="line-height: 16px;">Project Euler</a><span style="line-height: 16px;"> site. For those of you that may have stumbled in on these posts, and haven't read why I am doing this, you might want to go back to the beginning and find out here. The long and short of it is, I'm using these exercises as a way to solve fun problems while learning a new language (Scala). I've added a twist to try an help me think in a functional way - for each solution, I want my final version of code to have the least amount of mutable state possible.</span></span></div>
<div style="text-align: left;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;"><br /></span></span></div>
<div style="text-align: left;">
<span style="color: #333333; font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;">As it turns out, this has been a fun and enlightening exercise, and I'm only a few problems in! If you've read any of my previous posts, you know that they were concentrating on turning my Java-like, OO style code into more functional style code without any mutable state. I must be improving slightly, because this post is going to focus more on creating the right algorithm than on functional vs. OO style. Without further adieu, I present to you, Project Euler Problem 5:</span></span></div>
<div style="text-align: left;">
<span style="color: #333333;"></span></div>
<blockquote style="line-height: 16px;">
<span style="color: #333333;"><span style="font-family: Arial, Helvetica, sans-serif;">2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.<br />What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?</span></span></blockquote>
<div style="line-height: 16px;">
<span style="color: #333333;"><span style="font-family: Arial, Helvetica, sans-serif;">Well, my first solution, as always, was a brute-force way to solve the problem. I will simply find my 'upper limit' value, which is the product of all the numbers 11 to 20 (A very large number), and iterate all values up to that number, checking if each number has a remainder when divided by any of the numbers 11 to 20. Simple right? It was simple, but it also takes 2 minutes to run on my Lenovo ThinkPad running an Intel Dual Core i7 CPU @ 2.67GHz. Here's the implementation:</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif; font-size: small; line-height: 16px;">
<span style="color: #333333;"><br /></span></div>
<br />
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;">object Problem5 {</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> def divisible(number: BigDecimal): Boolean = {</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> for (i <- 11 to 20 ) {</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> if (number.remainder(new BigDecimal(i)).longValue > 0)</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> return false</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> }</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> return true</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> }</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"><br /></span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> def main(args: Array[String]): Unit = {</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> <span class="Apple-tab-span" style="white-space: pre;"> </span>var start = System.currentTimeMillis</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> val upperBound = (new BigDecimal(1) /: (11 to 20))(_ multiply new BigDecimal(_))</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> println("Upper bound is " + upperBound)</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> var i = 1</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> for (i <- 20 to upperBound.intValue() if divisible(new BigDecimal(i))) {</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> println("Smallest # divisible by 1 .. 20 is " + i);</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> println("Run time seconds " + ((System.currentTimeMillis()-start)/1000));</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> return</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> }</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;"> }</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif;">
<span style="color: #333333;"><span style="line-height: 16px;">}</span></span></div>
<div style="font-family: Verdana, Arial, sans-serif; font-size: small;">
<span style="color: #333333;"><span style="line-height: 16px;"><br /></span></span></div>
<span style="color: #333333;"><span style="line-height: 16px;"><span style="font-family: Arial, Helvetica, sans-serif;">After I solved the problem, I started thinking about it more. Iterating through every number seems wasteful, doesn't it? After all, there are a lot of numbers that will not evenly divide by ANY number in that sequence. So, I thought, I should really be iterating through a list of numbers that is the product of at least ONE of the numbers in the sequence. If I selected, 15, for instance, I could iterate through the list: (15, 30, 45, 60...). Of course, If I think about that more, the most efficient number to use will be the highest number in the list, 20. So, I created a new version of the code that iterates in increments of 20, and then checks to see if 11 to 19 are also divisible. This runs on my machine in about 2 seconds, making this about 60 times faster:</span></span></span><br />
<div style="font-family: Verdana, Arial, sans-serif; font-size: small;">
<span style="color: #333333;"><span style="line-height: 16px;"><br /></span></span></div>
<br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;">object Problem5 {</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> /*Let's skin this cat a different way...*/</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"><br /></span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> def main(args: Array[String]): Unit = {</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> for (i <- 1 to 320000000) {</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> val mot = i * 20;</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> val divisibleByAll = fitsAll(mot)</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> if (divisibleByAll) {</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> println("Smallest is " + mot);</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> return</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> }</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> }</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"><br /></span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> def fitsAll(number: Int): Boolean = {</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> for (i <- 11 to 19) {</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> if (number % i > 0)</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> return false;</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> }</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> return true</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> }</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;"> }</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace;"><span style="line-height: 16px;">}</span></span></span><br />
<span style="color: #333333;"><span style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"><span style="line-height: 16px;"><br /></span></span></span><br />
<span style="color: #333333;"><span style="font-family: Arial, Helvetica, sans-serif;"><span style="line-height: 16px;">I think I can further improve this code with some of Scala's features. For instance, I think I can iterate the sequence 1 to 320000000 by increments of 20 without needing the variable mot. Notince, though, that I do not have any mutable variables in the code - I declare 2 variables, but they are both val and not var, and so cannot be re-assigned. I don't think this is 'perfect functional thinking', but I suspect, I'm slowly catching on.</span></span></span><br />
<br />
<div style="font-family: Verdana, Arial, sans-serif; font-size: small;">
<span style="color: #333333;"><span style="line-height: 16px;"><br /></span></span></div>
<br />Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-17068983711615352532011-12-23T12:42:00.000-08:002012-01-07T13:22:46.117-08:00Project Euler Problem 4 in ScalaThis is 4 in a series. The previous post is at, <a href="http://benarchie.blogspot.com/2011/12/project-euler-problem-3-in-scala.html">Project Euler Problem 3 in Scala</a>.<br />
<br />
So I've already worked through 3 problems in Euler in hopes of using the exercises to help me learn some Scala. In each of the previous solutions, I had a LOT of mutable state in my code. As I get more comfortable with the language, however, I think I'm improving quite a bit. Even so, it appears I still had a mutable variable in my first solution to this problem. Problem 4 on the Project Euler site reads:<br />
<br />
<blockquote class="tr_bq">
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.<br />
Find the largest palindrome made from the product of two 3-digit numbers.</blockquote>
This doesn't seem too difficult to solve. We can cast our integer values to strings, reverse them, and compare them to determine if they are a palindrome, and iterating all the 3 digit numbers, 100-999 is easy. So, here's my first solution:<br />
<br />
<span style="font-family: 'Courier New', Courier, monospace;"> object Problem4 {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><br /></span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> def main(args: Array[String]): Unit = { </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>var highestPalendrome = 0;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> for(i <- 100 to 999) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>for(y <- 100 to 999) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> var product = i * y;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> var productStr = product toString;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> if(productStr.reverse equals(productStr)) { </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> println(productStr)</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> highestPalendrome = highestPalendrome max product;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>}</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>}</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> println("Highest is " + highestPalendrome);</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;">}</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"><br /></span><br />
<span style="font-family: inherit;">In this solution I iterate the numbers and store the highest palendrome as I go. Of course, the purpose of doing these exercises is to try and code without mutable state, so I had to get rid of that pesky highestPalendrome variable. To do this, I took advantage of the Scala fold left facilities. Turns out, this is a handy way to iterate a list and record results. Here's version 2:</span><br />
<span style="font-family: inherit;"><br /></span><br />
<br />
<span style="font-family: 'Courier New', Courier, monospace;">object Problem4 {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> def main(args: Array[String]): Unit = { </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>val highestPalendrome = (0 /: (100 to 999))((highest, next)=>{</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>(0 /: (100 to 999))((tot2, nex2)=>{</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> val product = next*nex2;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> if(product.toString.reverse.equals(product.toString)) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> next*nex2</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> } else {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> tot2</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>}) max highest </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>})</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> println("Highest is " + highestPalendrome);</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;">}</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"><br /></span><br />
You'll notice that this is essentially 1 statement, if you remove the main method and println. You should also notice that I'm using some of Scala's syntactic goodness to make the code easier to read - the end of that statement, 'max highest' would be much uglier in Java - .max(highest). <br />
<br />
Well, on to #5. Maybe this time, I won't need a second iteration of the code...<br />
<br />Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-3684481849480885592011-12-23T12:28:00.000-08:002012-01-07T13:23:40.818-08:00Project Euler Problem 3 in Scala<span style="font-family: Arial, Helvetica, sans-serif;">This is 3 in a series. The previous post is at, <a href="http://benarchie.blogspot.com/2011/10/project-euler-problem-2-in-scala.html">Project Euler Problem 2 in Scala</a>.</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">I've been busy again this fall, but now that I have a couple of days off over the holiday, I thought I'd play around with some more Scala. It is pretty slow going learning the language at this pace, but the day job calls...</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">Problem 3 on the Euler site states:</span><br />
<blockquote class="tr_bq">
<span style="font-family: Arial, Helvetica, sans-serif;">The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?</span></blockquote>
<span style="font-family: Arial, Helvetica, sans-serif;">For this solution, I reused the isPrime method from an earlier problem. Essentially I end up looping through all the values up to the square root of the number and record the primes. The largest prime is the last one.</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">Here's my first solution:</span><br />
<br />
<span style="font-family: 'Courier New', Courier, monospace;">object Problem3 {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> val number : Long = 600851475143L;</span><br />
<span class="Apple-tab-span" style="white-space: pre;"><span style="font-family: 'Courier New', Courier, monospace;"> </span></span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> def main(args: Array[String]): Unit = { </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>val sqrt = Math.sqrt(number);</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> var largest = 0L;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>var current : Long = 2L;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>while(current < sqrt.toLong) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> if(number % current == 0) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> if(isPrime(current)) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> <span class="Apple-tab-span" style="white-space: pre;"> </span>largest = current;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> current = current + 1L;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>} </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>println("Largest " + largest);</span><br />
<span class="Apple-tab-span" style="white-space: pre;"><span style="font-family: 'Courier New', Courier, monospace;"> </span></span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<br />
<span style="font-family: 'Courier New', Courier, monospace;"> </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> *//**</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> * Brute force method. Perhaps a better method </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> * can be implemented here? </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> *//*</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> def isPrime(number: Long) : Boolean = {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> var half = Math.sqrt(number) </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> var current = 2;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> while(current < half) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> if(number % current == 0) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> return false;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> current = current+1;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> return true;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;">}</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">After looking at my first solution to this problem, you can see that I have mutable state AGAIN. Something about my Object Oriented brain just can't seem to get into the stateless-state-of-mind. This is interesting for another reason, though. Mutable state, in general, isn't a particularly good thing. That is, if you can solve a programming problem without mutable state, it is better than the solution with mutable state. It shouldn't matter if you are using OO languages or Functional ones. It seems the industries years of OO teachings have led to we engineers sort of ignoring this fact. I guess mutable state isn't as clear in an OO language if you have good Encapsulation in your code, but its still something we should be paying attention to. Luckily, I was able to refactor my solution. Here's a better version:</span><br />
<br />
<br />
<span style="font-family: 'Courier New', Courier, monospace;">object Problem3 {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> val number : Long = 600851475143L;</span><br />
<span class="Apple-tab-span" style="white-space: pre;"><span style="font-family: 'Courier New', Courier, monospace;"> </span></span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> def main(args: Array[String]): Unit = { </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> println("Largest is " + largestPrime(2L, Math.sqrt(number), 2L));</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> @tailrec def largestPrime(initialPrime : Long, limit : Double, currentNumber : Long) : Long = {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> if(currentNumber >= limit.toLong) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> initialPrime</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> } else {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> if(isPrime(currentNumber) && number % currentNumber == 0) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> largestPrime(currentNumber, limit, currentNumber + 1);</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> } else {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> largestPrime(initialPrime, limit, currentNumber + 1);</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> /**</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> * Brute force method. Perhaps a better method </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> * can be implemented here? </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> */</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> def isPrime(number: Long) : Boolean = {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> var root = Math sqrt number</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> var current = 2;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> while(current < root) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> if(number % current == 0) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> return false;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> current = current+1;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> return true;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;">}</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">Here we have a new solution where all our mutable state has been removed. I start by declaring the number for which we are trying to find the largest prime. It is declared as a val, though, so we are guaranteed that the value can't change. This is different than any other language I've used, but it seems a handy facility. Next, I call the recursive largestPrime method, which uses Tail recursion to iterate the list. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">Of course, I still think there is a better way to determine if a number is prime or not, but this method is pretty efficient the way it is.</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">That's my solution for now. Stay tuned for Problem 4....</span><br />
<br />Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-81422388910747703792011-10-21T15:09:00.000-07:002012-01-07T13:25:13.394-08:00Project Euler Problem 2 in ScalaThis is 2 in a series. The Previous post is at, <a href="http://benarchie.blogspot.com/2011/10/project-euler-and-scala-problem-1.html">Project Euler and Scala Problem 1</a>.<br />
<br />
Here is the second problem on the Project Euler(PE) site.<br />
<br />
<blockquote>
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:<br />
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...<br />
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</blockquote>
<br />
<br />
Once again, I was able to solve this pretty easily, but I had lots of mutable state in my code. Here was my first solution:<br />
<br />
<br />
<span style="font-family: 'Courier New', Courier, monospace;">object Problem2 {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>val fourMillion : Integer = 4000000;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><br />
</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>var first : Integer = 0;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>var second : Integer = 1;</span><br />
<span class="Apple-tab-span" style="white-space: pre;"><span style="font-family: 'Courier New', Courier, monospace;"> </span></span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>def nextFib() : Integer = {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>var returnValue:Integer = prev1+prev2;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>return returnValue;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>}</span><br />
<span class="Apple-tab-span" style="white-space: pre;"><span style="font-family: 'Courier New', Courier, monospace;"> </span></span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>var sum : Long = 0;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><br />
</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>def main(args: Array[String]): Unit = { </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> var next:Integer = 0;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> while( (next <= fourMillion) ) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> next = nextFib();</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> if(next % 2 == 0) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> sum = sum + next;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> print(sum)</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>}</span><br />
<span style="font-family: 'Courier New', Courier, monospace;">}</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"><br />
</span><br />
<span style="font-family: inherit;">You will see that I have 3 mutable variables in there - first, second, and sum. I also have a rather ugly while loop. I'd like to get rid of the iteration here and use recursion instead. While doing so, I can also get rid of the mutable state. Here is the rewritten code:</span><br />
<br />
<br />
<span style="font-family: 'Courier New', Courier, monospace;">object Problem2 {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>//Tail recursive...</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>def fibList(currentList : Array[Int], limit : Int, previous : Int) : Array[Int] = {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> if(previous > limit) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> </span><span style="background-color: transparent; font-family: 'Courier New', Courier, monospace;">return currentList;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>} </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span></span><span style="background-color: transparent; font-family: 'Courier New', Courier, monospace;"> return fibList((currentList :+ previous), limit, (currentList.last + previous));</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>}</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><br />
</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>def main(args: Array[String]): Unit = { </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> print((0 /: fibList(Array[Int](0,1), 4000000, 1))((total, next)=> {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> if(next % 2 == 0) { </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> next + total</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> } else {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> total</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> } </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> }))</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>}</span><br />
<span style="font-family: 'Courier New', Courier, monospace;">}</span><br />
<br />
<span style="font-family: inherit;"><br />
</span><br />
<span style="font-family: inherit;">I hope you notice the comment in there - Tail Recursive. This is a very interesting feature of Scala, and most other functional languages. You see, the big concern in Java when using recursion is that you run out of stack space for all your recursions. In Scala, the compiler can optimize this code and get rid of the stack if you don't need to keep state in your method. I've carefully constructed the fibList here so that it can be optimized. This way, we can't fill up the stack. go ahead, change 4000000 to 4000000000. While you may overflow the int values, the recursive function won't blow up the memory. </span><br />
<span style="font-family: inherit;"><br />
</span><br />
<span style="font-family: inherit;">This feature of the language is really quite interesting, and from my understanding not a small feat to pull off given the current bytecode standard. This could allow for some very long-running calculations that might otherwise have caused memory problems if done other ways. </span><br />
<span style="background-color: transparent; font-family: inherit;"><br />
</span><br />
<span style="background-color: transparent; font-family: inherit;">That's all for this problem. On to #3... </span><br />
<span style="font-family: inherit;"><br />
</span>Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com2tag:blogger.com,1999:blog-3060516345583304229.post-91621447046942221462011-10-15T08:56:00.000-07:002012-01-07T13:25:49.220-08:00Project Euler and Scala problem 1<span style="font-family: Arial, Helvetica, sans-serif;">I recently found a Web site called, <a href="http://www.projecteuler.net/">Project Euler</a> (PE). Its a site full of problems that are intended to be solved by coding. As I am also experimenting with<a href="http://www.scala-lang.org/"> Scala</a>, I figured this would be a fun way to keep my skills sharp solving problems while learning the nuances of another language. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">What I am finding is very interesting. First, my 'functional' skills need work. I'm attempting to solve each problem with no mutable state, but as you will see, my first iteration usually has some sort of mutable state and it takes me a little bit to refactor it. Part of this is due to the fact that I spend my day job programming in an OO language, part of it is due to learning Scala, but part of it is just that I need more practice in the functional way of thinking. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">I am fortunate in that I have two friends who are also interested in PE and who have started working through the problems as well, so we swap notes after we solve the solutions, which further helps understanding. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">I thought I would blog about the problems as I work through them. The format I have settled on this this:</span><br />
<br />
<ol>
<li><span style="background-color: transparent; font-family: Arial, Helvetica, sans-serif;">I will present my first, rough, solution to the problem, along with a brief summary of the PEdocumentation.</span></li>
<li><span style="background-color: transparent; font-family: Arial, Helvetica, sans-serif;">I will present a refactored version of the same problem that makes the code much more functional and maintainable.</span></li>
<li><span style="background-color: transparent; font-family: Arial, Helvetica, sans-serif;">If the PE documentation reveals a math or programming concept that would improve the code, another version of the algorithm may be posted.</span></li>
</ol>
<span style="background-color: transparent; font-family: Arial, Helvetica, sans-serif;"><span style="background-color: transparent; font-family: Arial, Helvetica, sans-serif;">It's my hope that presenting my progress in this fashion is both interesting and revealing for other programmers. I work primarily in Java, so this might also be a good way for Java programmers to see how things translate to Scala. Of course I am not a Scala expert, so I'm sure there will be lots of comments with room for improvement. At least, that's my hope.</span><br />
<span style="background-color: transparent; font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
Here is PE's first problem:</span><br />
<div style="background-color: white;">
<blockquote>
<span style="font-family: Arial, Helvetica, sans-serif;">If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</span><span style="font-family: Arial, Helvetica, sans-serif;">Find the sum of all the multiples of 3 or 5 below 1000.</span></blockquote>
</div>
<div style="background-color: white;">
<span style="background-color: white; font-family: Arial, Helvetica, sans-serif;">Well, this seems simple enough. Simply iterate all the numbers to 1000, testing if they are divisible by 3 or 5 along the way. The first version of my code looks like this:</span></div>
<div style="background-color: white;">
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span></div>
<div style="background-color: white;">
</div>
<span style="font-family: 'Courier New', Courier, monospace;">object Problem1 {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><br /></span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> def main(args: Array[String]): Unit = { </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> var sum = 0;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> for( i <- Iterator.range(0,1000) if i % 3 == 0 || i % 5 == 0) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> sum += i;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> print(sum);</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;">}</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">There's nothing inherently wrong with the code above. Except I have that mutable variable, sum, in there. So, what's a more functional way to think about this? Thanks to the inspiration from my co-worker, Sean, we have a more functional version of the code above:</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: 'Courier New', Courier, monospace;">object Problem1 {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> def main(args: Array[String]): Unit = {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> val count = (1 to 999);</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> val sum = (0 /: count)((total, next) =></span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> if (next % 3 == 0 || next % 5 == 0) {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> total + next;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> } else {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> total;</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> });</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> println(sum);</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;">}</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">In this version, we've made the sum immutable (by using val instead of var), so it can only be assigned once. We've also used the left-fold operator, \:, to iterate the range. Finally, we've converted the contents of the for loop to a function block that gets executed on each 'fold'. This version looks pretty good, but after reviewing the PE docs, we pick up another little math trick. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">Instead of iterating the numbers, we can take the sum of all the multiples of 3, sum of all the multiples of 5 and then subtract all the multiples of 15. There's also a proof that demonstrates how to find the sum (I won't reprint it here, if you are interested, unlock the problem on the PE site).</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">The final version of our code looks like:</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: 'Courier New', Courier, monospace;">object Problem1 {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> def main(args: Array[String]): Unit = {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span> println(sumDivisibleBy(999,3) + sumDivisibleBy(999, 5) - sumDivisibleBy(999, 15));</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> def sumDivisibleBy(limit:Int, divisor:Int) : Int = {</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>val p = limit/divisor;<span class="Apple-tab-span" style="white-space: pre;"> </span> </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><span class="Apple-tab-span" style="white-space: pre;"> </span>divisor * (p*(p+1))/2; </span><br />
<span style="font-family: 'Courier New', Courier, monospace;"> }</span><br />
<span style="font-family: 'Courier New', Courier, monospace;">}</span><br />
<span style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">So in the end, we don't iterate the range at all. This solution would also scale well (what if we wanted to add all the multiples of 3 and five for all numbers under 1 million...)</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;">So there it is. A brief walk through my process on Project Euler problem 1. Let me know what you think.</span>Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-6003516080789888552011-07-17T08:44:00.000-07:002011-07-17T08:44:18.660-07:00GWT JSNI ReferenceI've recently had to go through the GWT JSNI interface, and I found the documentation a little lacking. While the official JSNI page has nice examples and clearly shows how things integrate, it leaves out some reference information that would be helpful. My guess is that they didn't want to duplicate the JNI reference, but its still a little frustrating to have to look up the type codes in a separate area. And the type codes aren't exactly intuitive, I mean, who would guess that 'Z' is the representation for boolean?<br />
<br />
So, here is a little cheat sheet for those of you looking for the GWT JSNI type codes. These are, of course, the same codes that can be found in the JNI reference. <br />
<br />
<table class="wikitable"><tbody>
<tr> <th>Native Type</th> <th>Java Language Type</th> <th>Description</th> <th>Type signature</th> </tr>
<tr> <td>unsigned char</td> <td>jboolean</td> <td>unsigned 8 bits</td> <td>Z</td> </tr>
<tr> <td>signed char</td> <td>jbyte</td> <td>signed 8 bits</td> <td>B</td> </tr>
<tr> <td>unsigned short</td> <td>jchar</td> <td>unsigned 16 bits</td> <td>C</td> </tr>
<tr> <td>short</td> <td>jshort</td> <td>signed 16 bits</td> <td>S</td> </tr>
<tr> <td>long</td> <td>jint</td> <td>signed 32 bits</td> <td>I</td> </tr>
<tr> <td><br />
long long<br />
<br />
__int64</td> <td>jlong</td> <td>signed 64 bits</td> <td>J</td> </tr>
<tr> <td>float</td> <td>jfloat</td> <td>32 bits</td> <td>F</td> </tr>
<tr> <td>double</td> <td>jdouble</td> <td>64 bits</td> <td>D</td> </tr>
</tbody></table><br />
Table taken from <a href="http://en.wikipedia.org/wiki/Java_Native_Interface">Wikipedia</a>, 5/7/2011<br />
<br />
<br />
In addition to the primitive types, any object can be referenced using its fully qualified name like this:<br />
<br />
LFully.Qualified.Name;<br />
<br />
For example, to access a string, you use: Ljava.lang.String;<br />
<br />
To reference an array of the same type, prepend [ like this:<br />
<br />
[Ljava.langString;<br />
<br />
So that's my quick cheat sheet. Here are a couple of additional references that help:<br />
<br />
<a href="http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasicsJSNI.html">Coding Basics - Javascript Native Interface (JSNI) </a><br />
<br />
<table><tbody>
<tr><td class="webkit-line-content"><a href="http://download.oracle.com/javase/6/docs/technotes/guides/jni/">JDK 6 Java Native Interface-related APIs & Developer Guides</a></td></tr>
</tbody></table>Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-14603872024395838812011-04-28T17:35:00.000-07:002011-04-28T17:35:01.994-07:00Master of Software EngineeringFinally, I am an MSE. That's, Master of Software Engineering. I just finished presenting my capstone project at <a href="http://www.carrollu.edu/">Carroll University</a>. <br />
<br />
A lot of people don't know what Software Engineering is. Is it related to Development? Is it really an Engineering discipline? I'd like to take this time to talk a little bit about what I think a Software Engineer is. <br />
<br />
Let's start with the official definition of 'Software Engineer'. Any search these days starts with Wikipedia, and in fact, Wikipedia has a nice listing for 'Software Engineering', with lots of references. Here is the first paragraph:<br />
<br />
<blockquote>Software engineering (SE) is a profession dedicated to designing, implementing, and modifying software so that it is of higher quality, more affordable, maintainable, and faster to build. It is a "systematic approach to the analysis, design, assessment, implementation, test, maintenance and re-engineering of a software by applying engineering to the software".[1] The term software engineering first appeared in the 1968 NATO Software Engineering Conference, and was meant to provoke thought regarding the perceived "software crisis" at the time.[2][3] Since the field is still relatively young compared to its sister fields of engineering, there is still much debate around what software engineering actually is, and if it conforms to the classical definition of engineering.[4] The IEEE Computer Society's Software Engineering Body of Knowledge defines "software engineering" as the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software, and the study of these approaches; that is, the application of engineering to software.[5] It is the application of Engineering to software because it integrates significant mathematics, computer science and practices whose origins are in Engineering.[6]</blockquote>Wikipedia, Dec 24, 2010<br />
<br />
If I were to put that rather lengthy description into my own short words, it would be: Software Engineering is a way to build better software by studying and applying a systematic, disciplined and quantifiable approach to the development process. <br />
<br />
You see, to me, the key characteristic is that while Software Engineering includes software development, it really goes beyond just writing code or applications. It is the study and practice of the processes that will make writing applications better. Better may not mean faster or cheaper but will always mean higher quality. Although, sometimes, it will mean faster and cheaper, but usually in the long run. So Software Engineering really expands into all the different tasks surrounding a system - business definition, requirements gathering, analysis, design, testing, and support. A Software engineer should know about all these phases in the life cycle and should be involved with all of them. <br />
<br />
But developing software is not exactly akin to designing a bridge or a car. There's still a component of craftsmanship or artistry involved with software development. Methodologies can be used to improve estimates, quality, and outcomes, but there is also a large component that is more akin to writing a novel or creating a movie than to building a bridge or designing a car.<br />
<br />
It is in that part of the software development process where the <i>art </i>of development presents itself. Writing software is a creative and abstract task with many different ways to solve a problem. In some cases, a single, best, solution can be found, but in so many others, there isn't one. In that regard, some developers are artists, some developers really aren’t, and never will be. The rest of us are aspiring to be one of the great ones. We are competent technicians, writing our works, but not gifted with the ability to produce masterpieces. Here is where what we learn and the techniques we apply from Software Engineering Study allow us to produce pieces of software that are in fact, solid and elegant. We won't be writing the next Mona Lisa, but by following proper techniques, using the best practices, studying what works, and applying them consistently and rigorously, we can produce consistent, appealing work with high levels of quality. If we work hard, people might one day also recognize us as an artist. <br />
<br />
Perhaps not a Michelangelo, but maybe a Bob Ross.Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com2tag:blogger.com,1999:blog-3060516345583304229.post-51618612586368753082011-04-24T10:40:00.000-07:002011-04-24T10:40:10.655-07:00My First Scala AppI've been looking at learning another development language for some time. Over the years I've dabbled in PHP, Groovy, and even C/C++. While I learned a lot in doing this, I never became an 'expert' in any of them. For the most part, I used them for the project in which they were needed or for the scenario where they were most appropriate and then went back to Java for my primary development platform. <br />
<br />
The reason is that I'd become so familiar with the Java tool set, language, and available libraries. I was (and am) most productive in that environment. But Java is showing its age and limitations. Its becoming clear that some of the most vexing problems facing developers will need a full range of tools to solve them, and while Java's OO support is good, its functional support is not. I, therefore, decided that I needed to expand and really learn another language pretty well. I decided that language is going to be Scala.<br />
<br />
Why Scala? Well, I'll go over that in a different post. This post is about my experience writing my first Scala app. So, here it goes.<br />
<br />
<b>The Application</b><br />
Since I am changing jobs (again), I decided I would leave something behind for my co-workers. In our current work environment, we have a shared drive where server error logs are stored in 'pseudo' XML format. It was always annoying to me that we had to navigate the file structure, open a text file, and hunt through the file to find an error we would be looking for. It was also difficult to determine how often an error was occurring. Now, the easy way to solve this is to use the log4j XML appender and read the files with Apache Chainsaw, but this is a large company, and it decided to go with a proprietary format. I decided to use Scala to write a little desktop app that the developers could use to view the log files in a tabular format, then select a row to see the stacktrace detail. <br />
<br />
<b>The Functionality</b><br />
The application needed 3 essential things : a table to show rows, a TextArea to show the detail, and a FileChooser to select which log to view. In the background it also needed the following processing capabilities: read in a file, modify the text to make it valid XML, parse the XML tags. That's about it.<br />
<br />
<b>The Results</b><br />
Well, I whipped out the app pretty quickly. It would have been much more quickly if I hadn't been learning Scala along the way. There were some really nice things about Scala that I found out. First, its swing wrapper classes are nice, and their pub/sub model is succinct. Second, the XML processing is excellent. The built in support for XML files allowed me to parse the logs in a couple of lines of code. Finally, the Actor metaphor for multi threading was also very easy to use and implement. <br />
<br />
I had a few frustrations along the way as well. The Eclipse plugin was nice, but it still doesn't have code-complete (One of the biggest productivity tools in my mind). The code-complete is supposed to be in the plugin, but for some reason, doesn't seem to work for me. I've tried on 3 separate computers. This meant that I was reading a lot of documentation. Its also hard to read the documentation. Since Scala has so much support for so many features, the docs can get a little complicated to read. I'm sure as I become more familiar with the libraries and syntax this will get easier, but I can see how it would be daunting for a junior developer.<br />
<br />
<b>Conclusion </b><br />
I'm by no means a Scala expert at this point, but I enjoyed the language enough, and it seems to have enough benefits that I'm looking forward to learning more. Who knows, maybe one day Scala will be my primary language...Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-48793232414080367832011-02-05T19:31:00.000-08:002011-02-05T19:31:59.461-08:00GWT and SmartGWT - JNI and Unsatisfied Link ErrorGWT uses the Java JNI mechanism in a really unique way. JNI was originally intended to work with native code on the computer where you had your JDK, like C++. I've had limited exposure to the JNI interface - I've only had to use it for a serial communication component. Even then, I was using a library that relied on JNI, so I didn't generate the code, I just had to make sure the native library was on my classpath.<br />
<br />
The Google Engineers applied this mechanism to Javascript, however. If you want to write 'Native' Javascript in your GWT classes, its easy. Just flag your method as native and put your javascript code, in comments, before your terminator. Here's a sample from the <a href="http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasicsJSNI.html#writing">Google Web site</a>.<br />
<br />
<span class="Apple-style-span" style="font-family: Helvetica, Arial, sans-serif; font-size: x-small;"></span><br />
<pre class="prettyprint" style="background-color: #fafafa; border-bottom-color: rgb(187, 187, 187); border-bottom-style: solid; border-bottom-width: 1px; border-left-color: rgb(187, 187, 187); border-left-style: solid; border-left-width: 1px; border-right-color: rgb(187, 187, 187); border-right-style: solid; border-right-width: 1px; border-top-color: rgb(187, 187, 187); border-top-style: solid; border-top-width: 1px; color: #007000; font-family: monospace; font-size: 9pt; line-height: 15px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 1em; overflow-x: visible; overflow-y: visible; padding-bottom: 0.99em; padding-left: 0.99em; padding-right: 0.99em; padding-top: 0.99em; white-space: pre-wrap; word-wrap: break-word;"><span class="kwd" style="color: #000088;">public</span><span class="pln" style="color: black;"> </span><span class="kwd" style="color: #000088;">static</span><span class="pln" style="color: black;"> </span><span class="kwd" style="color: #000088;">native</span><span class="pln" style="color: black;"> </span><span class="kwd" style="color: #000088;">void</span><span class="pln" style="color: black;"> alert</span><span class="pun" style="color: #666600;">(</span><span class="typ" style="color: #660066;">String</span><span class="pln" style="color: black;"> msg</span><span class="pun" style="color: #666600;">)</span><span class="pln" style="color: black;"> </span><span class="com" style="color: #880000;">/*-{
$wnd.alert(msg);
}-*/</span><span class="pun" style="color: #666600;">;</span></pre><br />
<br />
Viola! Instant native interface for your JavaScript CLIENT code. That's right, just try running this method on the server. While working on my current project, I ran into this issue accidently while trying to use a SmartGWT class. I got a JNI error on the server because the VM couldn't find the native code. Of course, there isn't any native code on the server. In this case, the 'native' code is JavaScript.<br />
<br />
I was trying to pass a SmartGWT ListGridRecord to the server so I could map it to a persistent bean. Of course, once I saw the error, I followed the inheritance hierarchy for ListGridRecord all the way up the chain, and what did I find at the top? JsObject. Of course, I didn't even have to go that far. After looking at the Record code, it relies on static methods in JSOHelper, which uses a lot of native JavaScript<br />
<br />
In the end I had make transfer objects to use to send the data over GWT RPC. This was a good reminder, though, that while GWT looks like Java, what's being executed really isn't.Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com0tag:blogger.com,1999:blog-3060516345583304229.post-65675582020599343152011-01-30T08:25:00.000-08:002011-01-30T08:25:10.038-08:00SmartGWT and GWT RPC IntegrationI am currently finishing my Capstone project for my <a href="http://www.carrollu.edu/gradprograms/softwareengineering/">MSE at Carroll University</a>. While the application I am writing itself doesn't have a lot of twists in it, I decided to use this opportunity to experiment with some different technologies. I'm using GWT, SmartGWT, and Hibernate in the application. I've used Hibernate and GWT pretty extensively in my professional career, but the twists I've added for this development are to configure Hibernate using the JPA standard, and to use GWT Designer for mockups. I've already posted about my experiences with <a href="http://benarchie.blogspot.com/2010/12/gwt-designer.html">GWT Designer</a>. <br />
<br />
I haven't really used SmartGWT before. My experience has been with the<a href="http://www.sencha.com/products/gwt/"> ExtGWT</a> library, which I loved. I chose to use <a href="http://code.google.com/p/smartgwt/">SmartGWT</a> on this build because it is fully LGPL, while Ext is dual licensed. While working with SmartGWT I've found some things that I was not expecting. <br />
<br />
One of the selling points of SmartGWT is that it has built in support for 'Data Binding' with Tables and the like. This is done through DataSource objects. The problem is, the published DataSource implementations don't work with GWT RPC. And the DataSource base class has dozens of methods (Just take a look at the<a href="http://www.smartclient.com/smartgwt/javadoc/com/smartgwt/client/data/DataSource.html"> JavaDoc</a>). It really isn't clear how to define your own custom data source, or the work it will take to do so. This was a sticking point for me because I really like the GWT RPC mechanism, and I had already come up with a nice security model, which I posted about<a href="http://benarchie.blogspot.com/2010/12/gwt-simple-security-configuration.html"> here</a>.<br />
<br />
It took a while, but I finally found a post about integrating GWT RPC on the <a href="http://forums.smartclient.com/showthread.php?t=4814">SmartClient Forums.</a> The post is a bit dated and says you need to compile from source, but that is not the case. The version of SmartGWT I am using, 2.4 already has the clientCustom flag built in. The developer who posted this also supplied 5 files, Including a GwtRpcDataSource abstract class, and a sample implementation. The class comments well what you need to do to implement your datasource. With this setup, a new GWT data source can be defined by implementing 4 methods. <br />
<br />
I hope this post helps others find the solution much faster than I was able to.Ben Arciszewskihttp://www.blogger.com/profile/02242641729372468998noreply@blogger.com2