You love the convinience of google photos but wondering how to use this free unlimited hosting to display images on you own web resources or maybe on livejournal?

I found a pretty easy straitforward solution for that:

  • Open the photo you need to embed on photos.google.com
  • Right click on it (context menu) and hit “inspect element”
  • Copy the line with the src=”…” - it containts the link to the physical addres of where Google stores this photo.
  • Now just use this src link on your web resource with the img html tag.
  • Profit!

Here is the screenshoot with what you need to find: Copy src

(Read More...)

When I was asked to make a program for solving a maze during the job interview for some reason I simply attempted to model a known human-friendly heuristics: follow the right wall. The resulting code was very long and somewhat hard although worked alright.

Now, during the algorithms class and review of DFS I decided to try the recursive approach for solving the maze. For starters let us create one:

1
2
3
4
5
6
7
8
9
10
11
12
# 0 clear
# 1 wall
# 2 was here
# 8 start
# 9 finish
maze = [
        [0, 0, 1, 0, 1],
        [0, 1, 0, 0, 0],
        [0, 1, 0, 1, 0],
        [0, 0, 0, 1, 0],
        [1, 1, 1, 0, 9]
]

Alternatively, we can feed the following txt file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
+--+--+--+--+--+--+--+--+--+--+
|             S|     |     |  |
+  +--+--+--+  +--+  +  +  +  +
|     |  |     |     |  |  |  |
+--+  +  +  +--+  +--+--+  +  +
|     |  |        |     |     |
+  +--+  +--+--+--+  +  +  +--+
|     |        |     |        |
+--+  +--+  +  +  +--+--+--+  +
|  |  |  |  |     |           |
+  +  +  +  +--+--+  +--+--+--+
|           |     |        |  |
+--+  +--+--+  +--+--+--+  +  +
|     |        |     |     |  |
+  +--+  +--+  +  +--+  +--+  +
|  |     |  |  |     |      F |
+  +  +--+  +  +--+  +--+--+  +
|  |  |     |     |  |     |  |
+  +  +  +--+--+  +  +  +--+  +
|     |              |        |
+--+--+--+--+--+--+--+--+--+--+

Which could be elegantly parsed into created above format:

1
2
3
def readMaze(filename):
    maze_mapping = {'S' : 0, 'F' : 9, ' ' : 0, '+' : 1, '-' : 1, '|' : 1}
    return [[maze_mapping[char] for char in line[:-1]] for line in open(filename)]

Now we need to know the properties of the maze and print it. For later I used tabulate package to print a list of lists as a table:

1
2
3
4
from tabulate import tabulate
width = len(maze)
height = len(maze[0])
print 'Maze width: %s, height %s' % (width, height)

Finally, the recursive function. The idea is simple: try to go in every direction recursively and if no wall, no out of bounds and was not here before - move on!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def move(x, y):
    global FoundWayOut
    if FoundWayOut:
        return

    print tabulate(maze)

    if (x < 0 or x > width - 1 or y < 0 or y > height - 1):
        print 'Out of bounds'; return
    if (maze[x][y] == 9):
        FoundWayOut = True
        print 'Got it!'; return
    if (maze[x][y] == 1):
        print 'That is wall'; return
    if (maze[x][y] == 2):
        print 'Was here before'; return
    maze[x][y] = 2

    move(x + 1, y) # East
    move(x, y + 1) # South
    move(x - 1, y) # West
    move(x, y - 1) # North

Now we can find the way out of the maze (if there is a way out):

1
2
3
move(0, 0)
if not FoundWayOut:
    print 'There is no way out of this!'

First call should be made from the start position.

Overall, recursive solution is way more elegant and easier to grasp as well as to implement.

(Read More...)

Bellman-Ford algorithm is easy and sufficiently efficient (E*V for straight forward implementation) for finding Shortest Paths (SP). Notably, it finds the shortests paths to ALL the other nodes in the graph.

The idea is simple: for each vertex we mantain the SP (init with inf) and if the precedent vertex + edge weight gives us better sum - then we update current SP value for that vertex.

Caveat: this algorithm fails if graph contains negative cycles since in that case one can obtain arbitrary small (negative) shortest path just by traversing this negative cycle over and over again.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
graph = {
    'a' : {'b' : 10, 'c' : 6},
    'b' : {'d' : 5},
    'c' : {'b' : 2},
    'd' : {}
}

def bellman_ford(graph, start_node):
    N = len(graph)
    sps = dict.fromkeys(graph.keys(), 'inf')
    sps[start_node] = 0
    print sps

    for i in xrange(N):
        # RELAX (for each edge)
        for start in graph.keys():
            adjacent_nodes = graph[start]
            for end in adjacent_nodes.keys():
                if sps[end] > sps[start] + adjacent_nodes[end]:
                    sps[end] = sps[start] + adjacent_nodes[end]
                    print sps

bellman_ford(graph, 'a')
(Read More...)

We have tree pegs with the discs on top of one another with decreasing size. Task is to move all disks from one peg to another while moving only one disk pertime and keeping smaller disks on biggers.

Recursive alg with the following idea: if we want to move 8 disks from peg1 to peg2, then we need to move 7 upper disks to the work peg first, then mode last to peg2 and then put 7 disks on top. Fist and last step is just an instance of Hanoi Tower problem once again, so we recursively call the function. Stopping condintion is if we want to move one disk only - then we just move.

Python impl:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
N_disks = 8
basicOperationCounter = 0

tower1 = [N_disks - i for i in xrange(N_disks)]
tower2 = []
tower3 = []

def printTowers():
    print tower1
    print tower2
    print tower3
    print '-------------------'

def moveDisk(out, to):
    disk = out[-1] # top element
    out.remove(disk)
    to.append(disk)

    global basicOperationCounter
    basicOperationCounter += 1
    printTowers()

def move(n, out, to, work):
    if n > 1:
        move(n - 1, out, work, to)
    moveDisk(out, to)
    if n > 1:
        move(n - 1, work, to, out)


printTowers()
move(N_disks, tower1, tower2, tower3)
print 'Move completed in %s steps. Theoretical bound is 2^n-1 = % s' % (basicOperationCounter, 2 ** N_disks - 1)
(Read More...)

Really nice way to check a potential candidate problem-solving skills is to test him as a mouse. How to find the way out of the maze? Programmically, of course.

From life experience we know, that the simpliest way to get out is to follow the right side and eventually we will find the exit.

Here is an example of the maze:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
+--+--+--+--+--+--+--+--+--+--+
|             S|     |     |  |
+  +--+--+--+  +--+  +  +  +  +
|     |  |     |     |  |  |  |
+--+  +  +  +--+  +--+--+  +  +
|     |  |        |     |     |
+  +--+  +--+--+--+  +  +  +--+
|     |        |     |        |
+--+  +--+  +  +  +--+--+--+  +
|  |  |  |  |     |           |
+  +  +  +  +--+--+  +--+--+--+
|           |     |        |  |
+--+  +--+--+  +--+--+--+  +  +
|     |        |     |     |  |
+  +--+  +--+  +  +--+  +--+  +
|  |     |  |  |     |      F |
+  +  +--+  +  +--+  +--+--+  +
|  |  |     |     |  |     |  |
+  +  +  +--+--+  +  +  +--+  +
|     |              |        |
+--+--+--+--+--+--+--+--+--+--+

The goal is to start from S and find F. Here is a possible solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

class coord{
	public int i;
	public int j;
	public coord(int i, int j){
		this.i = i;
		this.j = j;
	}
}

//Directions: 1 - right, 2 - up, 3 - left, 4 - down

public class Maze_solver {
	static String maze_filename = "maze.txt";
	static String route = "";
	static int last_move_direction = 2; //guess first direction
	static int[] directions = new int[]{4,1,2,3,4,1,2,3,4};	
	static boolean foundWayOut = false;
	@SuppressWarnings("serial")
	static HashMap<Integer, Character> direction_letters = new HashMap<Integer, Character>();
	                                  
	public static void main(String[] args) throws FileNotFoundException {
		initDirectionLetters()
		char[][] maze = readMaze(maze_filename);
		printMaze(maze);
		getOut(maze);
	}
	
	private void initDirectionLetters(){
		direction_letters.put(1, 'r');
		direction_letters.put(2, 'u');
		direction_letters.put(3, 'l');
		direction_letters.put(4, 'd');
	}
	
	private static char[][] readMaze(String filename) throws FileNotFoundException{
		Scanner sc = new Scanner(new BufferedReader(new FileReader(filename)));
		ArrayList<String> input = new ArrayList<String>();
		while (sc.hasNext())
			input.add(sc.nextLine());
		sc.close();
		
		int width = input.get(0).length(); 
		int height = input.size();		
		char[][] maze = new char[height][width];
		
		for (int j=0; j<height; j++){
			String line = input.get(j);
			for (int i=0; i < width; i++){
				maze[j][i] = line.charAt(i);
			}
		}
		
		return maze;
	}
	
	private static void printMaze(char[][] maze){
		for (int i=0; i < maze.length; i++){
			for (int j=0; j < maze[0].length; j++){
				System.out.print((char)maze[i][j]);
				System.out.print(" ");
			}
			System.out.println();
		}
	}
	
	private static void getOut(char[][] maze){
		coord coord = findStart(maze);
	    while (!foundWayOut){
	    	coord = makeMove(maze, coord);
	    	printMaze(maze);
	    }
		System.out.println(route);
	}
	
	static coord move(coord coord, int direction){
        coord new_coord = new coord(coord.i, coord.j);
        switch (direction){
        	case 1:
        		new_coord.j++;
        		break;
        	case 2:
        		new_coord.i--;
        		break;
        	case 3:
        		new_coord.j--;
        		break;
        	case 4:
        		new_coord.i++;
        		break;
        }        
        return new_coord;
    }
	
    static boolean checkIfGoodState(char[][] maze, coord coord){
    	if (maze[coord.i][coord.j] == 'F')
    		foundWayOut = true;
        return (maze[coord.i][coord.j] == ' ') ? true : false;
    }
    
    static coord makeMove(char[][] maze, coord coord){
        //try to do moves according to priority and break  
    	coord new_coord = null;
    	for (int i = last_move_direction - 1; i <= last_move_direction + 3; i++){
    		new_coord = move(coord, directions[i]);
    		if (checkIfGoodState(maze, new_coord)){
    			last_move_direction = directions[i];
    		    route += direction_letters.get(directions[i]);
    		    maze[new_coord.i][new_coord.j] = 'S';
    		    maze[coord.i][coord.j] = ' ';
    		    return new_coord;
    		}
    	}  		        
        return null; //shouldnt happen by assumption
    }
    
    static coord findStart(char[][] maze){
    	coord coord = new coord(0, 0);
        for (int i = 0; i < maze.length; i ++){
            for (int j = 0; j < maze[1].length; j ++){
               if (maze[i][j] == 'S'){
            	   coord.i = i;
            	   coord.j = j;
                   break;
               }
            }
        }
        return coord;
    }
}
(Read More...)