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.

Sunday, November 24, 2013

Moral Price Discrimination

   I just read The Armchair Economist by Steven E. Landsburg which was supplemental to the Microeconomics textbook I use for class. I'd definitely suggest it to anyone who has an interest in economics but is more of a beginner. Or you can check out his blog The Big Questions.A word of caution should be advised as Landsburg is very contrarian in his work and some of the ideas presented will definitely offend some people. I don't know enough about economics to support or criticize his ideas, but I really enjoy how they make me think.

       One of the big ideas of Microeconomics is price discrimination. The way I understand it, price discrimination works by transferring some of the consumer surplus to the producer. It does this by charging higher prices for a good to people who are willing to pay higher prices, and lower prices to people who would only buy the product at lower prices. If the price were higher but constant, the low-price people would not buy the product at all.

      One of the examples in the book was a company (can't remember which) that sold both a high speed and low speed printer. It sold the high speed version for $1500 (this was the 90's I think), and then it added a device that made the printer slower and sold that version for $1000. The two versions cost exactly the same to produce, yet one had been made intentionally worse and sold for a lower price. The people who wanted a high speed printer and had the money would buy the more expensive version, while the people who were more uncertain about either their need or ability to buy a printer would buy the cheaper version. The company makes more profit this way than it would by selling only the high speed one at either $1500 or $1000. Interesting. Price discrimination is everywhere if you look for it. Airlines do it regularly (ever wonder why a ticket for a connecting flight costs less even though the distance the plane takes you is longer than a direct flight?), as do colleges (if both tuition and financial aid are rising, what does that tell you?).
     
      Anyway I was at the grocery store the other day and stopped for a bit to look at the egg selection. Most of the eggs were from a company called Little Rhody's, while the rest were from a larger brand name. Little Rhody's was selling 6 different types of eggs. There was Large White Eggs ($2.59)*, Extra Large White ($2.79), Large Local Eggs ($2.79),  Extra Large Local ($2.99), Jumbo Large Local ($3.19), and Vegetarian Fed Large ($3.19).

       In order for a company to price discriminate they must have something resembling monopoly power (or else competitors will compete the high price down), and the product must not be able to be sold once it is bought (the people who bought at the low price would just resell the product at a price between the low price and the high price). So two things to consider: the grocery store was mostly dominated by Little Rhody's brand, and I doubt anyone would buy eggs from a stranger on the street. Then is this price discrimination? For sure some of the eggs do cost more to produce, as larger eggs must be produced by larger hens who eat more food, but how much of that extra cost is production cost and how much is discrimination? Does vegetarian feed cost that much more?  There was also cage-free eggs from the other brand that cost something like $3.49. I think I can see how extra production cost accounts for the price disparity in this case, but what about local eggs vs. outsourced eggs? Kind of makes you think about whats truly going on when we choose more ethically minded products.

     Sometimes I think that half the reason to buy any product that is "ethical" or "green" is because it costs more. If the more "ethical" product cost the same as the other choices I'd probably still buy it, but would I feel as good when I'm eating the eggs? Did I do my good deed for the day? Is it still morally right if I do something only because it gives me a release of dopamine?

I bought Extra Large Local.




*Most of these pries I remember well, while a couple are best guesses






Hey

Seeing as my writing has dropped to a high school level, I figured it was time to start a blog. That's what all of the experts suggest, right? I've been taking almost strictly math and science courses while at Brown, and right now it's really hard for me to convert thoughts into words. For the time being I will post here about whatever I'm working on or thinking about, without any particular rhyme or reason. Right now my particular interests are competitive sailing, mathematics, coding, weight lifting, and maybe a little bit of meditation. So to start, two things:

1) As soon as I created the blog I had two views, and one was from Alaska. How cool is that!

2) I was discussing what I think is my favorite probability question with a friend a few days ago:

A teacher is returning graded tests to her class of n students, none of which are labelled with a student's name. If she returns the tests at random, what is the expected number of students who get the correct test?

    \operatorname{E}[X] = x_1p_1 + x_2p_2 + \dotsb + x_kp_k \;.

Here expectation refers to the expected value, which is the sum of every value that the random variable X can take on, multiplied by the probability of obtaining that value.

For instance: flip a fair coin twice, what is the expected value if the value of heads=1 and tails=0?
E(X)=(0)(1/4)+(1)(1/2)+(2)(1/4)=1

I'm a little rusty on my formal probability, so I will just do this problem for a couple of cases, instead of proving it for the nth case.

Say that n=2:
then the E(X)=(0)(1/2)+2(1/2)=1
The probabilities here are determined as such because they only depend on the first person. If he gets the right test (P= 1/2) then the other person also gets the right test.

for n=3:
E(X)=(0)(1/3)+(1)(1/2)+(3)(1/6)=1
The trick here is that it's impossible to get 2 tests right and 1 wrong.

n=4:
E(X)=(1)(1/3)+(2)(1/4)+(4)(1/24)=1
(Using nCr/n! for probability of 2)


It's easy to see that this generalizes to the nth case (which is proved by linearity of expectation if I recall right). So no matter how many students the teacher has, she is expected to return just one test right!

Governing dynamics.