Pascal Triangle Generator in Python, and then in Haskell – The Gubatron Method

Here’s in python, imperatively, and then in functional style without the need for loops.


def pascal(n):
if n == 1:
return [ 1 ]
if n == 2:
return [ 1, 1 ]
prev = pascal(n1)
results = []
for i in range(n):
if i == 0:
continue
if i == n1:
break
results.append(prev[i] + prev[i1])
return [1] + results + [1]
# functional style, no loops
def pascal_fp(n):
if n == 1:
return [ 1 ]
prev = pascal_fp(n1)
return list(map(lambda x,y:x+y, [0] + prev, prev + [0]))

view raw

pascal.py

hosted with ❤ by GitHub

Here’s in Haskell, I call it the gubatron’s method, explained in the comments.
Saw it by looking at a pattern while trying to solve it in paper, it just clicked.
Not sure if this is how other people code this solution.


Gubatron's method
n=3 [1, 2, 1]
copy the list and append a 0 on the left of the first
and append a 0 at the end of the second
[0, 1, 2, 1]
[1, 2, 1, 0]
add them up!
n=4 [1, 3, 3, 1]
append 0s to both sides and add them up
n=4 [1, 3, 3, 1]
[0, 1, 3, 3, 1]
[1, 3, 3, 1, 0]
n=5 [1, 4, 6, 4, 1]
and so on
add two lists, for clarity
addLists :: Num c => [c] -> [c] -> [c]
addLists l1 l2 = zipWith (+) l1 l2
pascal :: (Eq a1, Num a1, Num a2) => a1 -> [a2]
pascal 1 = [ 1 ]
pascal n =
let prev = pascal(n1)
zero_prev = [0] ++ prev
prev_zero = prev ++ [0]
in
addLists zero_prev prev_zero
[1,2,3] -> "1 2 3"
listToString = unwords. map show
mapM_ -> map monadic so no weird IO errors are triggered
printTriangle n = mapM_ putStrLn (map listToString (map pascal [1..n]))
main = do
input <- getLine
printTriangle . (read :: String -> Int) $ input

view raw

pascal.hs

hosted with ❤ by GitHub

 

[CODE] Arduino 4 BIT LED binary counter

Here’s my “Hello World” on Arduino.
A 4-bit binary counter for arduino.
If you add another LED on the 5th pin, then it can count from 0 to 31 (32 values)

Circuit wired by @KataySantos

int counter = -1;
int MAX_VALUE = 16;

void updateLED(int pin, int bit, int ctr) {
  digitalWrite(pin, (ctr & (1<<bit)) == (1<<bit) ? HIGH : LOW);
}
void setup() {
  // this runs once
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
}

void loop() {
  // this runs repeatedly
  counter = (counter + 1) % MAX_VALUE;
  updateLED(1, 0, counter);
  updateLED(2, 1, counter);
  updateLED(3, 2, counter);
  updateLED(4, 3, counter);
  delay(500);
}

Top Eclipse (IDE) features I can’t live without

(If you are in Windows, replace “Cmd” for “Ctrl”, and “Option” for “Alt”)

Cmd + 1: Create variables out of function’s outputs, get suggestions to fix issues.

“Shift + Cmd + T”: Open Type.

“Shift + Cmd + R”: Open Resource.

Select element and press “Option + Cmd + R” to rename a class, variable, method, the refactor will be performed throughout the entire project flawlessly.

Select element and press “Cmd + T”: Show Type Hierarchy, great to know what classes implement an interface, or what classes extend an abstract class.

Android: How to obtain the WiFi’s corresponding NetworkInterface

Let’s say for some odd reason in the world you do need to get the corresponding NetworkInterface object of the Wifi on your android, in my case I needed to have my WiFi device send multicast packets, and I wanted my MulticastSocket to only send packets through the WiFi device (not 3g, or maybe even ethernet). The android API does not provide functionality to know what “NetworkInterface” your WiFi is using.

Here’s a solution proven in tens of different android phones, seems to work 100%.

[java]
public static NetworkInterface getWifiNetworkInterface(WifiManager manager) {

Enumeration<NetworkInterface> interfaces = null;
try {
//the WiFi network interface will be one of these.
interfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
return null;
}

//We’ll use the WiFiManager’s ConnectionInfo IP address and compare it with
//the ips of the enumerated NetworkInterfaces to find the WiFi NetworkInterface.

//Wifi manager gets a ConnectionInfo object that has the ipAdress as an int
//It’s endianness could be different as the one on java.net.InetAddress
//maybe this varies from device to device, the android API has no documentation on this method.
int wifiIP = manager.getConnectionInfo().getIpAddress();

//so I keep the same IP number with the reverse endianness
int reverseWifiIP = Integer.reverseBytes(wifiIP);

while (interfaces.hasMoreElements()) {

NetworkInterface iface = interfaces.nextElement();

//since each interface could have many InetAddresses…
Enumeration<InetAddress> inetAddresses = iface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress nextElement = inetAddresses.nextElement();
int byteArrayToInt = byteArrayToInt(nextElement.getAddress(),0);

//grab that IP in byte[] form and convert it to int, then compare it
//to the IP given by the WifiManager’s ConnectionInfo. We compare
//in both endianness to make sure we get it.
if (byteArrayToInt == wifiIP || byteArrayToInt == reverseWifiIP) {
return iface;
}
}
}

return null;
}

public static final int byteArrayToInt(byte[] arr, int offset) {
if (arr == null || arr.length – offset < 4)
return -1;

int r0 = (arr[offset] & 0xFF) << 24;
int r1 = (arr[offset + 1] & 0xFF) << 16;
int r2 = (arr[offset + 2] & 0xFF) << 8;
int r3 = arr[offset + 3] & 0xFF;
return r0 + r1 + r2 + r3;
}
[/java]

How to make your own Quick & Dirty Hex File Viewer in Java

Update: You might want to read this new version of the code instead. Thanks ispak

I was playing with a hex editor recently and then I thought it would be pretty easy to make a program to output what you see on a text editor. Here’s a quick & dirty Hex Visor I wrote in like 5 minutes with Java. It shows 15 bytes per line, and on the right side it prints all the visible characters of the ascii table, the non-visible ones are replaced with “.”

Enjoy:
[java]
//HexViewer.java
import java.io.*;

public final class HexViewer {
public final static void printFile(String filePath) {
File f;
try {
f = new File(filePath);
} catch (Exception e) {
return;
}

try {

FileInputStream fis = new FileInputStream(f);
while (fis.available() > 0) {
char[] line = new char[16];
for (int i=0; i < 16; i++) {
int readByte = fis.read();
String paddingZero = (readByte < 16) ? "0" : "";
System.out.print(paddingZero + Integer.toHexString(readByte) + " ");
line[i] = (readByte >= 33 && readByte <= 126) ? (char) readByte : ‘.’;
}
System.out.println(new String(line));
}
} catch (Exception e1) { e1.printStackTrace(); }
}

public final static void main(String[] args) {
if (args.length == 0)
return;

printFile(args[0]);
}
}
[/java]

Usage:
[bash]java HexViewer &lt;path to file> | less[/bash]

[bash]java HexViewer Desktop/Puppet.wmv | less

30 26 b2 75 8e 66 cf 11 a6 d9 00 aa 00 62 ce 6c 0&.u.f…….b.l
74 14 00 00 00 00 00 00 07 00 00 00 01 02 a1 dc t……………
ab 8c 47 a9 cf 11 8e e4 00 c0 0c 20 53 65 68 00 ..G………Seh.
00 00 00 00 00 00 f4 10 68 f9 49 76 2e 43 b5 9f ……..h.Iv.C..
09 0a 2d 19 45 7c 32 3a 24 00 00 00 00 00 70 ee ..-.E|2:$…..p.
14 06 fb da c7 01 28 01 00 00 00 00 00 00 00 8c ……(………
bb 53 00 00 00 00 10 88 dd 52 00 00 00 00 b8 0b .S…….R……
00 00 00 00 00 00 02 00 00 00 40 1f 00 00 40 1f ……….@…@.
00 00 90 50 02 00 b5 03 bf 5f 2e a9 cf 11 8e e3 …P….._……
00 c0 0c 20 53 65 61 10 00 00 00 00 00 00 11 d2 ….Sea………
d3 ab ba a9 cf 11 8e e6 00 c0 0c 20 53 65 06 00 …………Se..
33 10 00 00 a9 46 43 7c e0 ef fc 4b b2 29 39 3e 3….FC|…K.)9>
de 41 5c 85 27 00 00 00 00 00 00 00 01 00 0c 65 .A.’……….e
00 6e 00 2d 00 61 00 75 00 00 00 5d 8b f1 26 84 .n.-.a.u…]..&.
45 ec 47 9f 5f 0e 65 1f 04 52 c9 1a 00 00 00 00 E.G._.e..R……
00 00 00 02 01 ea cb f8 c5 af 5b 77 48 84 67 aa ……….[wH.g.
8c 44 fa 4c ca 62 01 00 00 00 00 00 00 06 00 00 .D.L.b……….
00 01 00 0c 00 02 00 02 00 00 00 49 00 73 00 56 ………..I.s.V
00 42 00 52 00 00 00 00 00 00 00 01 00 34 00 00 .B.R………4..
00 06 00 00 00 44 00 65 00 76 00 69 00 63 00 65 …..D.e.v.i.c.e
00 43 00 6f 00 6e 00 66 00 6f 00 72 00 6d 00 61 .C.o.n.f.o.r.m.a
00 6e 00 63 00 65 00 54 00 65 00 6d 00 70 00 6c .n.c.e.T.e.m.p.l
00 61 00 74 00 65 00 00 00 4c 00 31 00 00 00 00 .a.t.e…L.1….
00 02 00 0c 00 02 00 02 00 00 00 49 00 73 00 56 ………..I.s.V
00 42 00 52 00 00 00 01 00 00 00 02 00 34 00 00 .B.R………4..
00 0c 00 00 00 44 00 65 00 76 00 69 00 63 00 65 …..D.e.v.i.c.e
00 43 00 6f 00 6e 00 66 00 6f 00 72 00 6d 00 61 .C.o.n.f.o.r.m.a
00 6e 00 63 00 65 00 54 00 65 00 6d 00 70 00 6c .n.c.e.T.e.m.p.l
00 61 00 74 00 65 00 00 00 4d 00 50 00 40 00 4d .a.t.e…M.P.@.M
00 4c 00 00 00 00 00 01 00 2e 00 03 00 04 00 00 .L…………..
00 57 00 4d 00 2f 00 57 00 4d 00 41 00 44 00 52 .W.M./.W.M.A.D.R
00 43 00 50 00 65 00 61 00 6b 00 52 00 65 00 66 .C.P.e.a.k.R.e.f
00 65 00 72 00 65 00 6e 00 63 00 65 00 00 00 a7 .e.r.e.n.c.e….
3f 00 00 00 00 01 00 34 00 03 00 04 00 00 00 57 ?……4…….W
00 4d 00 2f 00 57 00 4d 00 41 00 44 00 52 00 43 .M./.W.M.A.D.R.C
00 41 00 76 00 65 00 72 00 61 00 67 00 65 00 52 .A.v.e.r.a.g.e.R
00 65 00 66 00 65 00 72 00 65 00 6e 00 63 00 65 .e.f.e.r.e.n.c.e
00 00 00 b0 06 00 00 74 d4 06 18 df ca 09 45 a4 …….t……E.
ba 9a ab cb 96 aa e8 a4 0d 00 00 00 00 00 00 00 …………….
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 …………….
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 …………….
[/bash]

This how it looks on a full blown hex editor like HexEdit:
Same file on HexEdit

The Code of HexViewer.java on emacs:
HexViewer.java on emacs

Screenshot of the output:
HexViewer in action

Homework
Hack the code so that it ouputs the first column shown on the HexEdit screenshot. That column represents the byte position of each row. It’s basically a counter incremented 16 units at the time, and shown in Hex.