Saturday, December 21, 2013

Portfolio

I've moved my math work to another website, which will act as my portfolio. Any employers who are reading this, follow this link to my work : https://seelio.com/lucasadams

Tuesday, December 10, 2013

Minimum Sum of 2 integers in a Vector

I answered this question on CareerCup:

Given the array of digits (0 is also allowed), what is the minimal sum of two integers that are made of the digits contained in the array. 
For example, array: 1 2 7 8 9. The min sum (129 + 78) should be 207

I assumed that numbers that begin with 0 (i.e 027) were invalid.


Ex:  V=1 2 3 4 5 6 7 8 9

ans=16047


Ex:  V=0 0 0 3 3 5 6 7

ans=6063


Here's the Matlab code I wrote:

function [S]=minsum(V)
% Returns the minimum sum of 2 integers using all of the digits in vector V
% ex. 12789 =179+28=207

if sum(V~=0)<2
    display('function cannot compute minimun sum if there are not at least 2 integers')
    return
end


v=sort(V)
L=numel(V);
n=sum(v==0);

if n~=0
    vnew(1:2)=v(n+1:n+2);
    vnew(3:(n+2))=0;
    vnew(n+3:L)=v(n+3:end);
    v=vnew
end
 

v1=v(1:2:end)
v2=v(2:2:end)
num1=0;
num2=0;




if mod(L,2)==0
 
    for i=1:L/2
        num1=num1+v1(i)*10^(L/2-i);
        num2=num2+v2(i)*10^(L/2-i);
    end
else
    for i=1:(L+1)/2
         num1=num1+v1(i)*10^((L+1)/2-i);
    end
 
    for j=1:(L-1)/2
        num2=num2+v2(j)*10^((L-1)/2-j);
    end
end
num1
num2
S=num1+num2



end


Saturday, December 7, 2013

Shortest Path Dynamic Program

Here's a short program I wrote for my Operations Research class. It computes the shortest path from anywhere in a grid to an endpoint. The inputs are C,c2,M,N,sp,L where C is an MxN grid where every point should be some large integer (L)  except for a group of points on the boundary, which should be zero and represent the endpoint. c2 is a secondary cost matrix size MxN which stores obstacles. Every point should be zero except for the points that represent obstacles which should again be a large integer (L). sp should be a 2x1 vector that contains the coordinates of the starting point. I used a helper function function [C,c2,M,N,sp,L]=conditions() to call my inputs, and used L=20,000 for the large integer. Here's a figure showing the optimal path:
And here's another:
Here's a surf graph that shows how the program computes the shortest distance to any point. It uses dynamic programming to compute the distance from each point to the end zone, by starting from the points that border the end zone and working outward. Because the algorithm can't see around corners very well, it is iterated multiple times, seeing one square further each time, until the whole grid is reached:
Here's the code. The main function is called robot and the helper is called conditions. Run time is about 30s:

Note: the program assumes a border surrounding the grid of width 1, which is why the for  loop runs from M-1:2 and N-1:2. 



function []=Robot(C,c2,M,N,sp,L)
% Computes the shortest distance and route from any point to an end state
% by dynamic programming, runtime is ~20s with 200x150 grid

% This function takes inputs C,c2,M,N,sp 
% C-> MxN grid with implicit boundary around edges
% the value of C should be some large integer (20000 in this case)
% everywhere except at the desired end state, which should be 0
% c2-> secondary cost, MxN grid that is 0 everywhere and some large integer (20000)
% wherever there is an obstacle
% sp-> starting point on the MxN grid


clear all

% I call the given conditions, to use a different starting point redefine
% sp after conditions line
[C,c2,M,N,sp,L]=conditions();


count=0;

a=1;
b=0;

% This will iteratively loop the grid C to compute the shortest distance
% it stops when the # of points in C>20000 stops changing
while a~=b
a=sum(sum(C>=L));

% This computes the shortest distance to the end state by looking at each
% of the 8 directions, it stores the distance in C and the direction in D
% The boundary around the grid is implied by the bounds of the for loops
% It works through the entire grid backwords from the end state
for i=M-1:-1:2
    for j=N-1:-1:2
       m(1)=C(i+1,j)+c2(i+1,j)+1;
       m(2)=C(i,j+1)+c2(i,j+1)+1;
       m(3)=C(i-1,j)+c2(i-1,j)+1;
       m(4)=C(i,j-1)+c2(i,j-1)+1;
       m(5)=C(i+1,j+1)+c2(i+1,j+1)+sqrt(2);
       m(6)=C(i+1,j-1)+c2(i+1,j-1)+sqrt(2);
       m(7)=C(i-1,j-1)+c2(i-1,j-1)+sqrt(2);
       m(8)=C(i-1,j+1)+c2(i-1,j+1)+sqrt(2);
       [Y,I]=min(m); 
       C(i,j)=Y;
       D(i,j)=I;
    end
end
b=sum(sum(C>=20000))

count=count+1
end


% This part of the code uses the matrix D, which stores the direction of
% the shortest path from any point in the grid, and computes and plots
% the path by starting at sp

G=zeros(M,N);
G(sp(1),sp(2))=1;


while C(sp(1),sp(2))~=0
    if D(sp(1),sp(2))==1
        sp=sp+[1,0];
    elseif D(sp(1),sp(2))==2
        sp=sp+[0,1];
    elseif D(sp(1),sp(2))==3
        sp=sp+[-1,0];
    elseif D(sp(1),sp(2))==4
        sp=sp+[0,-1];
    elseif D(sp(1),sp(2))==5
        sp=sp+[1,1];
    elseif D(sp(1),sp(2))==6
        sp=sp+[1,-1];
    elseif D(sp(1),sp(2))==7
        sp=sp+[-1,-1];
    else 
        sp=sp+[-1,1];
    end
    G(sp(1),sp(2))=1;
end

figure(1)
% This plots the trajectory
hold on
for i=1:M
    for j=1:N
        if G(i,j)==1
            plot(i,j,'.')
        end
    end
end

figure(2)
surf(C','LineStyle','none')
view(2)
colorbar
axis tight
caxis([0 500])









function [C,c2,M,N,sp,L]=conditions();

clear;


M=200;
N=150;

%%% starting point sp
sp = [130,40];

L=20000;    % Large number L instead of infinity

%%% Terminal C(s) function %%%
C=L*ones(M,N);
C(M,N-4:N)=0;

%%% obstacle condition = c2(s)%%%
c2 = zeros(M,N);
c2(M-30:M,129:130)=L;
c2(40:42,30:N)=L;
c2(10:30,120:140)=L;
c2(60:100,40:100)=L;
c2(140:142,1:50)=L;
c2(160:162,20:N)=L;
c2(162:190,110:112)=L;
c2(170:200,90:92)=L;
c2(162:190,70:72)=L;
c2(100:140,45:47)=L;



figure(1);
hold on;
grid on;
% plot obstacle
for i=1:M;
    for j=1:N;
        if c2(i,j) ~= 0;
            plot(i,j,'gs','linewidth',1)
        end
    end
end

% plot starting point with black dot
plot(sp(1),sp(2),'ko','linewidth',7);

% plot door (exit point) with red squares
plot(M,N-4:N,'rs','linewidth',3);

% plot wall
line([1,M],[1,1],'color','b','linewidth',2);
line([1,M],[N,N],'color','b','linewidth',2);
line([1,1],[1,N],'color','b','linewidth',2);
line([M,M],[1,N],'color','b','linewidth',2);
xlim([0 M+1])
ylim([0 N+1])








Thursday, November 28, 2013

Discipline

     I remember in social psychology learning about willpower as a muscle*. One study had participants doing some very boring and repetitive task, like placing pegs in different holes. After this initial task the participants were asked to solve a complicated geometric problem. The control group, who didn't have to do the initial task, worked longer on the geometric problem, while the other group gave up earlier. This showed the depletion aspect of willpower. In another study they had participants practice doing things that required willpower throughout the week. At the end of the week they had to solve some sort of puzzle and performed better on this task than the control who did not practice during the week. This showed the strengthening aspect of willpower.
   
     I've been thinking a lot about willpower as a muscle the last couple days and how this concept relates to sailing. Our season ended this fall on a disappointing note: the coed team didn't qualify for the Atlantic Coast Championships, the first time in something like 13 years. At the time our team was ranked 6th in the country so this was a big blow, and I felt a lot of the weight on my shoulders as the top skipper on the team. When it was over our coaches emphasized the need for a sense of urgency, a kind of fired-up attitude. To someone not in the sport the speech would be understood as: try harder.
   

     Sailing is odd because it combines the mental aspects of golf with the tactical and strategic elements of chess, to which it adds the the technical aspect of any other sport. Can you imagine someone telling a golf player they needed to try harder to make a shot? Or a chess player that they needed to try harder to outsmart the other player? No, clearly a different sort of effort must be made to improve in those disciplines.
   
     Willpower will take your game to the next level. Thinking back, at the end of the last school year I had that sense of urgency my coaches were talking about. I was fired up- angry, frankly- and felt I had no time to waste. I gathered a selection of my dad's sailing books and set to work reading them. I was determined to get better, and I did. The books definitely helped, as did sailing a few days a week every week, but what I think really made the difference was that I flexed my willpower muscle everyday. In my fired-up state I forced myself to do every task that needed to be done as soon as I could. Tax forms, emails, working out, whatever- as soon as the thought popped into my head I did it. In other words, I exercised my willpower, and I got stronger. This lasted throughout most of the summer, until I became complacent. At the end of the fall I was certainly "trying" as hard as ever, but something just wasn't the same.
 
      A lot of sailors, and people from other sports for that matter, have said something along the lines of "I know what to do but for some reason I don't do it" at some point in their recreational careers. This fall I said that exact line after doing something particularly dumb in practice. After replaying the race in my head I observed that I had an internal voice that was telling me all of the right things to do ( "we should step back out to the left side, we're over-leveraged in the middle") and a second voice that raised doubts or gave alternative decisions. What I've just realized is that that first voice you hear when sailing is the same voice involved in willpower. When a thought pops in your head that says "I should do my laundry" and you do it, that builds the same strength used to make the right decision in sailboat racing.
   
      Some may be wondering why you need anything but instinct to make the right decision in sailing. The answer is that for most situations you don't. For good sailors the right decision comes naturally. But the hard decisions require discipline, especially when the ego's involved. A simple example would be covering 2 boats on the last beat coming in to the finish. A voice in your head says "there's no way you can cover both boats if they split sides, pick one to cover and stick with it". Instead of listening you decide that actually there is really good breeze in the middle and you think you can catch both the left and right shift. You catch neither, and both boats pass you. With discipline the decision becomes easy: pick one boat and don't worry if the other beats you as you can't control the breeze.
     As I wait for the start of the spring season I will be training both my body and my mind.

Flex that willpower muscle, through discipline watch it grow

* Doing some research I came across a blog that had some interesting objections to the depletion aspect of willpower. Check it out http://www.epjournal.net/blog/2011/08/willpower-is-not-a-resource/

Wednesday, November 27, 2013

Rock Paper Scissors Lizard Spock

       So I'm enrolled in a Python programming course on Coursera and just finished my first project! I haven't really been working on this class due to my time constraints from my actual classes at Brown and from sailing, but now that I'm on break I thought I would give it a shot. The program is really simple: it plays a round of Rock-Paper-Scissors (just realized my code uses the word "Scizzors" not scissors, really need to work on my spelling)-Lizard-Spock with you.
       For those who don't know RPSLS is an expansion of rock paper scissors made popular by the T.V show The Big Bang Theory. I used Code Skulptor to write and execute my code, and it's saved through their website. To play a game of RPSLS, just scroll down to the end of the script. At the bottom there is a line that says:
rpsls("Spock") 
     To play the game just replace "Spock" with any of the 5 words (or just leave it as Spock). This is what you choose to throw. Then click the run button, which is a triangle shaped button in the upper left corner. The computer will randomly pick one of the five throws and show you who won.

Not the coolest thing in the world but it's a start.
Here's the link:

http://www.codeskulptor.org/#user26_SeeLm0xDrq_2.py

Traffic

    Is traffic an unavoidable consequence of our transportation infrastructure? Couldn't there be a more efficient way to get cars from here to there? I certainly don't know the answer to this question, but often let it distract my mind while I'm in some bumper to bumper congestion. The other day after getting my skates sharpened I was led on a detour goose chase on my way back to the highway. The pack of cars I was stuck with followed the signs as we made over 10 turns, even though we only hundreds of feet away.

        I tried to think of an algorithm that would get us going in the right direction faster. Maybe some sort of large scale linear program, in the style of game theory. Each car would choose his best possible route based on the most likely decision of the other cars in the area. It doesn't seem like that scenario is too futuristic, as cars doubling as WiFi hotspots are becoming mainstream. Soon cars will be able to talk to each other and will operate on a virtual grid. Once we have autonomous cars optimization becomes a real possibility. Google's self driving car has been on the road for over a year now. Of course, the security concerns with allowing our vehicles to have their own internet and be autonomous are serious. Hopefully by that time encryption outruns clever hackers.
 

Monday, November 25, 2013

Simulation of Random Homework Assignment Problem

I simulated the random assignment on Matlab for a few cases:



The convergence is similar no matter how many students there are. The error after 1000 trials (I used Error=|average-1|) hovers around 0.02 regardless of the number of students.