Tuesday, July 22, 2014

How to Embed Python in C++

#include <iostream>
#include <string>
#include <Python.h>

using namespace std;

int main() {
    Py_Initialize();

    string statements =
        "a = 8\n"
        "b = 2\n"
        "c = (a * b) / 2";

    int retVal = PyRun_SimpleString(statements.c_str());
    if (retVal == 0) {
        PyObject* m = PyImport_AddModule("__main__");
        PyObject* v = PyObject_GetAttrString(m, "c");

        int c = PyInt_AsLong(v);
        cout << "c: " << c << endl;

        Py_DECREF(v);
    }
    Py_Finalize();
    return 0;
}
Output:
c: 8

Wednesday, March 26, 2014

How to Solve Diagonal Print

Given a string and a number, and print the string diagonally filling in empty space with periods and going down as many lines as the given number. So "Peter piper picked a peck of pickled peppers" with n = 10 becomes
P.........r......... .........i.........p...
.e......... .........p.........c.........e..
..t.........p.........e.........k.........r.
...e.........i.........c.........l.........s
....r.........c.........k.........e.........
..... .........k......... .........d........
......P.........e.........o......... .......
.......i.........d.........f.........P...... 
........p......... ......... .........e.....
.........e.........a.........p.........p....
package main

import (
    "fmt"
    "os"
    "strconv"
)

func main() {
    str := os.Args[1]
    n, _ := strconv.Atoi(os.Args[2])
    for i := 0; i < n; i++ {
        for k := 0; k < i; k++ {
            fmt.Print(".")
        }
        for j := 0; j < len(str)-i; j++ {
            if (j % n == 0 && j+1 < len(str)) {
                fmt.Print(string(str[j+i]))
            } else {
                fmt.Print(".")
            }
        }
        fmt.Println()
    }
}

Sunday, January 12, 2014

How to Convert a BST to a Doubly Linked List In-Place

Problem:
Convert a BST to a doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list.
package main

import (
    "fmt"
)

type Node struct {
    Value int
    Left  *Node
    Right *Node
}

type LinkedList struct {
    Front *Node
    Back  *Node
}

// this is the actual algorithm that converts a BSt into a doubly linked list
// the rest of the code is just to make unit testing easier
func (l *LinkedList) ToLinkedList(node *Node) {
    if node == nil {
        return
    }
    l.ToLinkedList(node.Left)
    node.Left = l.Back
    if l.Back != nil {
        l.Back.Right = node
    } else {
        l.Front = node
    }
    l.Back = node
    l.ToLinkedList(node.Right)
}

type BST struct {
    Root *Node
}

func (b *BST) Add(value int) {
    b.Root = b.add(b.Root, value)
}

func (b *BST) add(node *Node, value int) *Node {
    if node == nil {
        return &Node{value, nil, nil}
    }
    if node.Value > value {
        node.Left = b.add(node.Left, value)
    } else if node.Value < value {
        node.Right = b.add(node.Right, value)
    }
    return node
}

func main() {
    values := []int{8, 3, 10, 1, 6, 14, 4, 7, 13}
    bst := BST{}
    for _, v := range values {
        bst.Add(v)
    }
    ll := LinkedList{}
    ll.ToLinkedList(bst.Root)
    for n := ll.Front; n != nil; n = n.Right {
        fmt.Print(n.Value, " ")
    }
    fmt.Println()
    for n := ll.Back; n != nil; n = n.Left {
        fmt.Print(n.Value, " ")
    }
    fmt.Println()
}
Output:
1 3 4 6 7 8 10 13 14 
14 13 10 8 7 6 4 3 1

Tuesday, January 7, 2014

How to Force Kill a Process in Java

In Java, there is no easy way to force a termination of a process spawned in Java. Calling Process.destroy() does not guarantee that the process will be terminated. Although Java 8 might fix this with Process.destroyForcibly(), if you still use older versions of Java, you are out of luck. Below is a not-so-portable solution to terminate a process on Linux and Windows using Java Native Runtime. You could also use JNA or JNI to invoke the OS native API.
package test;

import java.lang.reflect.Field;

import jnr.ffi.LibraryLoader;
import jnr.ffi.Pointer;
import jnr.ffi.Runtime;

public class Test {
    public static interface Kernel32 {
        boolean TerminateProcess(Pointer handle, int exitCode);
    }
    
    public static interface Posix {
        int kill(int pid, int sig);
    }
    
    public static void main(String[] args) throws Exception {
        ProcessBuilder pb = new ProcessBuilder(args[0]);
        Process p = pb.start();
        System.out.println("Sleeping for 5 seconds");
        Thread.sleep(5000);
        p.destroy();
        if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
            if (p.getClass().getName().equals("java.lang.Win32Process") ||
                p.getClass().getName().equals("java.lang.ProcessImpl")) {
                Field f = p.getClass().getDeclaredField("handle");
                f.setAccessible(true);
                long handle = f.getLong(p);
                
                System.out.println("Killing process");
                Pointer ptr = Pointer.wrap(Runtime.getSystemRuntime(), handle);
                int exitCode = 0;
                Kernel32 kernel32 = LibraryLoader.create(Kernel32.class).load("Kernel32");
                kernel32.TerminateProcess(ptr, exitCode);
            }
        } else {
            if (p.getClass().getName().equals("java.lang.UNIXProcess")) {
                Field f = p.getClass().getDeclaredField("pid");
                f.setAccessible(true);
                int pid = f.getInt(p);
                
                System.out.println("Killing process");
                Posix posix = LibraryLoader.create(Posix.class).load("c");
                posix.kill(pid, 9);
            }
        }
    }
}

Wednesday, November 6, 2013

How to Embed Python into C++

Below is a simple example how to embed Python into C++.
#include <iostream>
#include <Python.h>

int main(int argc, char* argv[]) {
    Py_Initialize();
    PyRun_SimpleString("import math; a = 100; result = math.log10(100)");
    PyObject* module = PyImport_AddModule("__main__");
    PyObject* dictionary = PyModule_GetDict(module);
    PyObject* result = PyDict_GetItemString(dictionary, "result");
    double resultValue = PyFloat_AsDouble(result);
    std::cout << "result: " << resultValue << std::endl;
    Py_Finalize();
    return 0;
}
Output:
result: 2

Thursday, October 31, 2013

How to Solve Max Volume Problem

My solution for max volume problem.
package main

import (
    "fmt"
)

func maxVolume(a []int) int {
    left := 0
    right := len(a) - 1
    volume := 0
    total := 0
    for left != right {
        if a[left] <= a[right] {
            for i := left + 1; i < len(a); i++ {
                if a[left] > a[i] {
                    volume += a[left] - a[i]
                } else {
                    left = i
                    total += volume
                    volume = 0
                    break
                }
            }
        } else {
            for i := right - 1; i >= left; i-- {
                if a[right] > a[i] {
                    volume += a[right] - a[i]
                } else {
                    right = i
                    total += volume
                    volume = 0
                    break
                }
            }
        }
    }
    return total
}

func main() {
    fmt.Println(maxVolume([]int{2, 5, 1, 2, 3, 4, 7, 7, 6}) == 10)
    fmt.Println(maxVolume([]int{2, 5, 1, 3, 1, 2, 1, 7, 7, 6}) == 17)
    fmt.Println(maxVolume([]int{2, 3, 1, 2, 3, 1, 3}) == 5)
    fmt.Println(maxVolume([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}) == 0)
    fmt.Println(maxVolume([]int{9, 8, 7, 6, 5, 4, 3, 2, 1}) == 0)
    fmt.Println(maxVolume([]int{1, 1, 1, 1, 1}) == 0)
    fmt.Println(maxVolume([]int{1, 0, 1}) == 1)
    fmt.Println(maxVolume([]int{5, 0, 5}) == 5)
    fmt.Println(maxVolume([]int{5, 0, 4}) == 4)
    fmt.Println(maxVolume([]int{4, 0, 5}) == 4)
    fmt.Println(maxVolume([]int{4, 0, 5, 0, 2}) == 6)
    fmt.Println(maxVolume([]int{0, 1, 0, 1, 0}) == 1)
    fmt.Println(maxVolume([]int{0, 1, 0, 0, 1, 0}) == 2)
    fmt.Println(maxVolume([]int{4, 2, 2, 1, 1, 1, 3}) == 8)
    fmt.Println(maxVolume([]int{0, 3, 2, 1, 4}) == 3)
    fmt.Println(maxVolume([]int{1, 0, 1, 0}) == 1)
    fmt.Println(maxVolume([]int{1, 0, 1, 2, 0, 2}) == 3)
    fmt.Println(maxVolume([]int{2, 5, 1, 2, 3, 4, 7, 7, 6}) == 10)
    fmt.Println(maxVolume([]int{5, 1, 0, 1}) == 1)
    fmt.Println(maxVolume([]int{2, 5, 1, 2, 3, 4, 7, 7, 6, 3, 5}) == 12)
    fmt.Println(maxVolume([]int{3, 0, 1, 0, 2}) == 5)
}

How to Solve Spiral Problem

My solution for spiral problem.
package main

import (
    "fmt"
)

func spiral(height, width, row, col int) []int {
    a := createSlice(height, width)
    result := []int{}
    r := row - 1
    c := col - 1
    result = append(result, a[r][c])
    x := 1
    for z := 0; (height * width) != len(result); z++ {
        for i := 0; i < x; i++ {
            r, c = up(r, c)
            if !outOfBoundary(height, width, r, c) {
                result = append(result, a[r][c])
            }
        }
        for i := 0; i < x; i++ {
            r, c = left(r, c)
            if !outOfBoundary(height, width, r, c) {
                result = append(result, a[r][c])
            }
        }
        x += 1
        for i := 0; i < x; i++ {
            r, c = down(r, c)
            if !outOfBoundary(height, width, r, c) {
                result = append(result, a[r][c])
            }
        }
        for i := 0; i < x; i++ {
            r, c = right(r, c)
            if !outOfBoundary(height, width, r, c) {
                result = append(result, a[r][c])
            }
        }
        x += 1
    }
    return result
}

func outOfBoundary(height, width, row, col int) bool {
    return !((row >= 0 && row < height) && (col >= 0 && col < width))
}

func left(row, col int) (int, int) {
    return row, col - 1
}

func right(row, col int) (int, int) {
    return row, col + 1
}

func up(row, col int) (int, int) {
    return row - 1, col
}

func down(row, col int) (int, int) {
    return row + 1, col
}

func createSlice(height, width int) [][]int {
    a := make([][]int, height)
    n := 1
    for i := 0; i < height; i++ {
        a[i] = make([]int, width)
        for j := 0; j < width; j++ {
            a[i][j] = n
            n += 1
        }
    }
    return a
}

func main() {
    fmt.Println(spiral(5, 5, 3, 3))
    fmt.Println(spiral(2, 4, 1, 2))
    fmt.Println(spiral(5, 5, 4, 2))
}