Prefix-function computation in Knuth-Morris-Pratt Algorithm - algorithm

So for the following sub string
1 2 3 4 5 6 7 8 9 10 11
a b c d a b c d a b x
Which is the prefix function? Me and one of my friends computed it and we have different results, mine is:
a b c d a b c d a b x
0 0 0 0 1 2 3 4 5 6 2
and his:
a b c d a b c d a b x
0 0 0 0 1 2 3 4 1 2 0
If I am wrong, why is that?

The prefix table should be:
a b c d a b c d a b x
0 0 0 0 1 2 3 4 5 6 0
so both versions given are not right.
For the last entry of your table
a b c d a b c d a b x
0 0 0 0 1 2 3 4 5 6 2
^
|
this one
to be correct, the suffix of length 2 of a b c d a b c d a b x which is b x would also have to be its length 2 prefix, which is a b instead.
In case of entries different from zero in the prefix table corresponding prefixes and suffixes have been marked in the table below:
a 0
a b 0
a b c 0
a b c d 0
a b c d a 1
-
=
a b c d a b 2
---
===
a b c d a b c 3
-----
=====
a b c d a b c d 4
-------
=======
a b c d a b c d a 5
---------
=========
a b c d a b c d a b 6
-----------
===========
a b c d a b c d a b x 0

My KMP function in java:
public int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
Result for prefix arrays:
[-1, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0]

Neither of your answers are correct. The prefix function or partial match table would be the following:
a b c d a b c d a b x
0 0 0 0 1 2 3 4 5 6 0
Your answer was correct upto index 10. But in the last index you have done something wrong. The reason why value of index 11 of partial match table would 0 is because there are no proper prefix which matches any proper suffix of the string upto index 11. Because all proper suffixes at this position will end with x and no proper prefix at this position will end with x.
If you have problem understanding what actually prefix function or partial index table means you can take a look into this document. It has a very good explanation. Hope it helps.

both of your answers are wrong. correct one will be
a b c d a b c d a b x
0 0 0 0 1 2 3 4 5 6 0

Related

How cap() of slice calculated? [duplicate]

This question already has answers here:
Why does the capacity of a slice change when you drop the first n items but not the last n items?
(2 answers)
Re-slicing slices in Golang
(2 answers)
Why exactly is there a CAPACITY parameter when creating a slice in Golang
(2 answers)
Decreasing slice capacity
(3 answers)
cap vs len of slice in golang
(3 answers)
Closed 9 months ago.
In the below code:
package main
import "fmt"
func main() {
b := make([]int, 0, 5)
fmt.Println(len(b), cap(b), b) // 0 5
c := b[:3]
fmt.Println(len(c), cap(c), c) // 3 5
d := c[1:5]
fmt.Println(len(d), cap(d), d) // 4 4
e := d[0:4]
fmt.Println(len(e), cap(e), e) // 4 4
}
underlying array for d is same as underlying array for b & c
Why cap(d) is 4?
lets break it down step by step
intialized b
b := make([]int, 0, 5) // which makes [ ] = length 0, with a cap of 5
fmt.Println(len(b), cap(b), b) // 0 5
b => c
c := b[:3] // which makes [ 0 0 0 ] = length 3, still a cap of 5
fmt.Println(len(c), cap(c), c) // 3 5
c => d
d := c[1:5] // which makes [ 0 0 0 0 ] = length of 4, now with a cap of 4
fmt.Println(len(d), cap(d), d) // 4 4
the reason for c[1:5] making the cap one less because it's technically erasing c[0] from the array... it's being completely sliced out of it.
visualization
array of 5
-------------
[ 0 0 0 0 0 ]
0 1 2 3 4
c[1:5] = [ x | 0 0 0 0 ]
^
this index of the array fell behind the sliced indexs and was
sliced out making the new cap is based off the array [ 0 0 0 0 ]
1 2 3 4
why didnt this happen with the others...?
-------------------------------------------
b[:3] = [ 0 0 0 | x x ]
^ ^
these two indexs of the array did not fall behind the
sliced indexs which means the cap remains at 5 [ 0 0 0 x x ]
1 2 3 4 5

Maxima- symbolic variable substitution in more algorithmic way

expJ:listarray(J);
(expJ) ["-(l[1]*l[3]*m[3]*('diff(r[3](t),t,1))^2*sin(r[3](t)-r[1](t))+(2*l[1]*l[2]*m[3]+l[1]*l[2]*m[2])*('diff(r[2](t),t,1))^2*sin(r[2](t)-r[1](t))-l[1]*m[1]*g*cos(r[1](t)))/2","-(l[2]*l[3]*m[3]*('diff(r[3](t),t,1))^2*sin(r[3](t)-r[2](t))+((-2*l[1]*l[2]*m[3])-l[1]*l[2]*m[2])*('diff(r[1](t),t,1))^2*sin(r[2](t)-r[1](t))-2*l[2]*m[2]*g*cos(r[2](t)))/2","(l[2]*l[3]*m[3]*('diff(r[2](t),t,1))^2*sin(r[3](t)-r[2](t))+l[1]*l[3]*m[3]*('diff(r[1](t),t,1))^2*sin(r[3](t)-r[1](t))+3*l[3]*m[3]*g*cos(r[3](t)))/2"]
for i:1 thru 3 do(
for k:1 thru 3 do(
J[i,1]:ssubst("m3","m[3]",J[i,1])
));
I wanna substitute numbers in front of m as they are 1,2,3 with algorithm, but when I put mi ,it recognizes this as different variable, so somehow I need to indicate ssubs("mi","m[i]",J[i,1]) as i is separate from m.
Any suggestions?
OK, here is a way to substitute v(k) for v[k]. I believe that's OK since Matlab recognizes parentheses for array subscripts.
%o5 is the input (as strings) which you gave above. I've parsed the strings in %o7 and extracted the list of subscripted variables (via sublist and subvarp) in %o10. From there I created a list v(k) = v[k] in %o14 and then substituted those back into the parsed expressions in %o15.
I hope that this is going in the direction that will be helpful to you. You might still need to modify this approach to get what you want, but in any event, I will repeat my very strong advice against string processing. If there is still something more to do, it is almost certainly better to achieve it by working with expressions than with strings.
(%o5) [-(l[1]*l[3]*m[3]*('diff(r[3](t),t,1))^2*sin(r[3](t)-r[1](t))+(2*l[1]*l[\
2]*m[3]+l[1]*l[2]*m[2])*('diff(r[2](t),t,1))^2*sin(r[2](t)-r[1](t))-l[1]*m[1]*\
g*cos(r[1](t)))/2, -(l[2]*l[3]*m[3]*('diff(r[3](t),t,1))^2*sin(r[3](t)-r[2](t)\
)+((-2*l[1]*l[2]*m[3])-l[1]*l[2]*m[2])*('diff(r[1](t),t,1))^2*sin(r[2](t)-r[1]\
(t))-2*l[2]*m[2]*g*cos(r[2](t)))/2, (l[2]*l[3]*m[3]*('diff(r[2](t),t,1))^2*sin\
(r[3](t)-r[2](t))+l[1]*l[3]*m[3]*('diff(r[1](t),t,1))^2*sin(r[3](t)-r[1](t))+3\
*l[3]*m[3]*g*cos(r[3](t)))/2]
(%i6) linel:65;
(%o6) 65
(%i7) map (parse_string, %o5);
d 2
(%o7) [((- l l m (-- (r (t))) sin(r (t) - r (t)))
1 3 3 dt 3 3 1
d 2
- (2 l l m + l l m ) (-- (r (t))) sin(r (t) - r (t))
1 2 3 1 2 2 dt 2 2 1
d 2
+ l m g cos(r (t)))/2, ((- l l m (-- (r (t)))
1 1 1 2 3 3 dt 3
d 2
sin(r (t) - r (t))) - ((- 2 l l m ) - l l m ) (-- (r (t)))
3 2 1 2 3 1 2 2 dt 1
sin(r (t) - r (t)) + 2 l m g cos(r (t)))/2,
2 1 2 2 2
d 2
(l l m (-- (r (t))) sin(r (t) - r (t))
2 3 3 dt 2 3 2
d 2
+ l l m (-- (r (t))) sin(r (t) - r (t))
1 3 3 dt 1 3 1
+ 3 l m g cos(r (t)))/2]
3 3 3
(%i8) grind (%);
[((-l[1]*l[3]*m[3]*('diff(r[3](t),t,1))^2*sin(r[3](t)-r[1](t)))
-(2*l[1]*l[2]*m[3]+l[1]*l[2]*m[2])
*('diff(r[2](t),t,1))^2*sin(r[2](t)-r[1](t))
+l[1]*m[1]*g*cos(r[1](t)))
/2,
((-l[2]*l[3]*m[3]*('diff(r[3](t),t,1))^2*sin(r[3](t)-r[2](t)))
-((-2*l[1]*l[2]*m[3])-l[1]*l[2]*m[2])
*('diff(r[1](t),t,1))^2*sin(r[2](t)-r[1](t))
+2*l[2]*m[2]*g*cos(r[2](t)))
/2,
(l[2]*l[3]*m[3]*('diff(r[2](t),t,1))^2*sin(r[3](t)-r[2](t))
+l[1]*l[3]*m[3]*('diff(r[1](t),t,1))^2*sin(r[3](t)-r[1](t))
+3*l[3]*m[3]*g*cos(r[3](t)))
/2]$
(%o8) done
(%i9) listofvars (%o7);
(%o9) [l , m , g, t, l , m , m , l ]
1 1 2 2 3 3
(%i10) sublist (%, subvarp);
(%o10) [l , m , l , m , m , l ]
1 1 2 2 3 3
(%i11) map (op, %o10);
(%o11) [l, m, l, m, m, l]
(%i12) map (args, %o10);
(%o12) [[1], [1], [2], [2], [3], [3]]
(%i13) map (lambda ([v], apply (op(v), args(v))), %o10);
(%o13) [l(1), m(1), l(2), m(2), m(3), l(3)]
(%i14) map (lambda ([v1, v2], v1=v2), %o10, %o13);
(%o14) [l = l(1), m = m(1), l = l(2), m = m(2), m = m(3),
1 1 2 2 3
l = l(3)]
3
(%i15) subst (%, %o7);
d 2
(%o15) [((- l(1) l(3) m(3) (-- (r (t))) sin(r (t) - r (t)))
dt 3 3 1
d 2
- (2 l(1) l(2) m(3) + l(1) l(2) m(2)) (-- (r (t)))
dt 2
sin(r (t) - r (t)) + l(1) m(1) g cos(r (t)))/2,
2 1 1
d 2
((- l(2) l(3) m(3) (-- (r (t))) sin(r (t) - r (t)))
dt 3 3 2
d 2
- ((- 2 l(1) l(2) m(3)) - l(1) l(2) m(2)) (-- (r (t)))
dt 1
sin(r (t) - r (t)) + 2 l(2) m(2) g cos(r (t)))/2,
2 1 2
d 2
(l(2) l(3) m(3) (-- (r (t))) sin(r (t) - r (t))
dt 2 3 2
d 2
+ l(1) l(3) m(3) (-- (r (t))) sin(r (t) - r (t))
dt 1 3 1
+ 3 l(3) m(3) g cos(r (t)))/2]
3
(%i16) grind (%);
[((-l(1)*l(3)*m(3)*('diff(r[3](t),t,1))^2*sin(r[3](t)-r[1](t)))
-(2*l(1)*l(2)*m(3)+l(1)*l(2)*m(2))
*('diff(r[2](t),t,1))^2*sin(r[2](t)-r[1](t))
+l(1)*m(1)*g*cos(r[1](t)))
/2,
((-l(2)*l(3)*m(3)*('diff(r[3](t),t,1))^2*sin(r[3](t)-r[2](t)))
-((-2*l(1)*l(2)*m(3))-l(1)*l(2)*m(2))
*('diff(r[1](t),t,1))^2*sin(r[2](t)-r[1](t))
+2*l(2)*m(2)*g*cos(r[2](t)))
/2,
(l(2)*l(3)*m(3)*('diff(r[2](t),t,1))^2*sin(r[3](t)-r[2](t))
+l(1)*l(3)*m(3)*('diff(r[1](t),t,1))^2*sin(r[3](t)-r[1](t))
+3*l(3)*m(3)*g*cos(r[3](t)))
/2]$
(%o16) done
(%i17) listofvars (%o15);
(%o17) [g, t]

awk skipping records. getline command

this is a task related to data compression using fibonacci binary representation.
what i have is this text file:
result.txt
a 20
b 18
c 18
d 15
e 7
this file is a result of scanning a text file and counting the appearances of each char on the file using awk.
now i need to give each char its fibonacci-binary representation length.
since i'm new to ubuntu and teminal, i've done a program in java that receives a number and prints all the fibonacci codewords length up to the number and it's working.
this is exactly what i'm trying to do here. the problem is that it doesn't work...
the length of fibonacci codewords is also work as fibonnaci.
these are the rules:
f(1)=1 - there is 1 codeword of length 1.
f(2)=1 - there is 1 codeword of length 2.
f(3)=2 - there is 2 codeword of length 3.
f(4)=3 - there is 3 codeword of length 4.
and so on...
(i'm adding on more bit to each codeword so the first two lengths will be 2 and 3)
this is the code i've made: its name is scr5
{
a=1;
b=1;
len=2
print $1 , $2, len;
getline;
print $1 ,$2, len+1;
getline;
len=4;
for(i=1; i< num; i++){
c= a+b;
g=c;
while (c >= 1){
print $1 ,$2, len ;
if (getline<=0){
print "EOF"
exit;
}
c--;
i++;
}
a=b;
b=c;
len++;
}}
now i write on terminal:
n=5
awk -v num=$n -f scr5 a
and there are two problems:
1. it skips the third letter c.
2. on the forth letter d, it prints the length of the first letter, 2, instead of length 3.
i guess that there is a problem in the getline command.
thank u very much!
Search Google for getline and awk and you'll mostly find reasons to avoid getline completely! Often it's a sign you're not really doing things the "awk" way. Find an awk tutorial and work through the basics and I'm sure you'll see quickly why your attempt using getlines is not getting you off in the right direction.
In the script below, the BEGIN block is run once at the beginning before any input is read, and then the next block is automatically run once for each line of input --- without any need for getline.
Good luck!
$ cat fib.awk
BEGIN { prior_count = 0; count = 1; len = 1; remaining = count; }
{
if (remaining == 0) {
temp = count;
count += prior_count;
prior_count = temp;
remaining = count;
++len;
}
print $1, $2, len;
--remaining;
}
$ cat fib.txt
a 20
b 18
c 18
d 15
e 7
f 0
g 0
h 0
i 0
j 0
k 0
l 0
m 0
$ awk -f fib.awk fib.txt
a 20 1
b 18 2
c 18 3
d 15 3
e 7 4
f 0 4
g 0 4
h 0 5
i 0 5
j 0 5
k 0 5
l 0 5
m 0 6
The above solution, compressed form :
mawk 'BEGIN{ ___= __= _^=____=+_ } !_ { __+=(\
____=___+_*(_=___+=____))^!_ } $++NF = (_--<_)+__' fib.txt
a 20 1
b 18 2
c 18 3
d 15 3
e 7 4
f 0 4
g 0 4
h 0 5
i 0 5
j 0 5
k 0 5
l 0 5
m 0 6

Create file with matched and non-matched records using Pig script

Can you please suggest on below file matching logic and removing duplicate entries using Pig -
1) Removing duplicate entries based on key RoleId-
InputFile1
--------------
RoleId Name
1 A
2 B
3 C
2 D
5 E
5 F
7 G
OutpufFile1 (Only unique records)
RoleId Name
1 A
3 C
7 G
OutpufFile2 (Capture duplicate records)
RoleId Name
2 B
2 D
5 E
5 F
2) File Matching key is RoleId -
InputFile1 InputFile2
----------- ----------
RoleId Name RoleId Age
1 A 1 20
2 B 2 21
3 C 1 22
4 D 2 23
5 E 3 24
7 25
OutpufFile1 (Matching records) OutputFile2 (Un-matching from 1st)
-------------------- -----------
RoleId Name Age RoleId Name
1 A 20, 22 4 D
2 B 21, 23 5 E
3 C 24
Thanks,
Can you try the below approach?
Problem1 Solution:
input
1 A
2 B
3 C
2 D
5 E
5 F
7 G
PigScript:
A = LOAD 'in.txt' USING PigStorage() AS(RoleId:int,Name:chararray);
B = GROUP A BY RoleId;
C = FOREACH B GENERATE FLATTEN($1) AS(RoleId,Name),COUNT(A) AS cnt;
SPLIT C INTO Distval IF (cnt==1), NonDistVal IF (cnt>=2);
D = FOREACH Distval GENERATE RoleId,Name;
STORE D INTO 'DistFile' USING PigStorage();
E = FOREACH NonDistVal GENERATE RoleId,Name;
STORE E INTO 'NonDistFile' USING PigStorage();
Output:
cat DistFile/part-r-00000
1 A
3 C
7 G
cat NonDistFile/part-r-00000
2 B
2 D
5 E
5 F
Problem2 Solution:
InputFile1
1 A
2 B
3 C
4 D
5 E
InputFile2
1 20
2 21
1 22
2 23
3 24
7 25
PigScript:
A = LOAD 'InputFile1' USING PigStorage() AS(RoleId:long, Name:chararray);
B = LOAD 'InputFile2' USING PigStorage() AS(RoleId:long, Age:int);
C = COGROUP A BY RoleId ,B BY RoleId;
D = FILTER C BY NOT IsEmpty(A);
SPLIT D INTO RoleMatch IF NOT IsEmpty(B),NoRoleMatch IF IsEmpty(B);
E = FOREACH RoleMatch GENERATE FLATTEN($1),BagToTuple(B.Age);
STORE E INTO 'RoleMatchFile' USING PigStorage();
F = FOREACH NoRoleMatch GENERATE FLATTEN($1);
STORE F INTO 'NoRoleMatchFile' USING PigStorage();
Output:
cat RoleMatchFile/part-r-00000
1 A (20,22)
2 B (21,23)
3 C (24)
cat NoRoleMatchFile/part-r-00000
4 D
5 E

Code-golf: generate pascal's triangle

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Generate a list of lists (or print, I don't mind) a Pascal's Triangle of size N with the least lines of code possible!
Here goes my attempt (118 characters in python 2.6 using a trick):
c,z,k=locals,[0],'_[1]'
p=lambda n:[len(c()[k])and map(sum,zip(z+c()[k][-1],c()[k][-1]+z))or[1]for _ in range(n)]
Explanation:
the first element of the list comprehension (when the length is 0) is [1]
the next elements are obtained the following way:
take the previous list and make two lists, one padded with a 0 at the beginning and the other at the end.
e.g. for the 2nd step, we take [1] and make [0,1] and [1,0]
sum the two new lists element by element
e.g. we make a new list [(0,1),(1,0)] and map with sum.
repeat n times and that's all.
usage (with pretty printing, actually out of the code-golf xD):
result = p(10)
lines = [" ".join(map(str, x)) for x in result]
for i in lines:
print i.center(max(map(len, lines)))
output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
K (Wikipedia), 15 characters:
p:{x{+':x,0}\1}
Example output:
p 10
(1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1)
It's also easily explained:
p:{x {+':x,0} \ 1}
^ ^------^ ^ ^
A B C D
p is a function taking an implicit parameter x.
p unfolds (C) an anonymous function (B) x times (A) starting at 1 (D).
The anonymous function simply takes a list x, appends 0 and returns a result by adding (+) each adjacent pair (':) of values: so e.g. starting with (1 2 1), it'll produce (1 2 1 0), add pairs (1 1+2 2+1 1+0), giving (1 3 3 1).
Update: Adapted to K4, which shaves off another two characters. For reference, here's the original K3 version:
p:{x{+':0,x,0}\1}
J, another language in the APL family, 9 characters:
p=:!/~#i.
This uses J's builtin "combinations" verb.
Output:
p 10
1 1 1 1 1 1 1 1 1 1
0 1 2 3 4 5 6 7 8 9
0 0 1 3 6 10 15 21 28 36
0 0 0 1 4 10 20 35 56 84
0 0 0 0 1 5 15 35 70 126
0 0 0 0 0 1 6 21 56 126
0 0 0 0 0 0 1 7 28 84
0 0 0 0 0 0 0 1 8 36
0 0 0 0 0 0 0 0 1 9
0 0 0 0 0 0 0 0 0 1
Haskell, 58 characters:
r 0=[1]
r(n+1)=zipWith(+)(0:r n)$r n++[0]
p n=map r[0..n]
Output:
*Main> p 5
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1]]
More readable:
-- # row 0 is just [1]
row 0 = [1]
-- # row (n+1) is calculated from the previous row
row (n+1) = zipWith (+) ([0] ++ row n) (row n ++ [0])
-- # use that for a list of the first n+1 rows
pascal n = map row [0..n]
69C in C:
f(int*t){int*l=t+*t,*p=t,r=*t,j=0;for(*t=1;l<t+r*r;j=*p++)*l++=j+*p;}
Use it like so:
int main()
{
#define N 10
int i, j;
int t[N*N] = {N};
f(t);
for (i = 0; i < N; i++)
{
for (j = 0; j <= i; j++)
printf("%d ", t[i*N + j]);
putchar('\n');
}
return 0;
}
F#: 81 chars
let f=bigint.Factorial
let p x=[for n in 0I..x->[for k in 0I..n->f n/f k/f(n-k)]]
Explanation: I'm too lazy to be as clever as the Haskell and K programmers, so I took the straight forward route: each element in Pascal's triangle can be uniquely identified using a row n and col k, where the value of each element is n!/(k! (n-k)!.
Python: 75 characters
def G(n):R=[[1]];exec"R+=[map(sum,zip(R[-1]+[0],[0]+R[-1]))];"*~-n;return R
Shorter prolog version (112 instead of 164):
n([X],[X]).
n([H,I|T],[A|B]):-n([I|T],B),A is H+I.
p(0,[[1]]):-!.
p(N,[R,S|T]):-O is N-1,p(O,[S|T]),n([0|S],R).
another stab (python):
def pascals_triangle(n):
x=[[1]]
for i in range(n-1):
x.append(list(map(sum,zip([0]+x[-1],x[-1]+[0]))))
return x
Haskell, 164C with formatting:
i l=zipWith(+)(0:l)$l++[0]
fp=map (concatMap$(' ':).show)f$iterate i[1]
c n l=if(length l<n)then c n$' ':l++" "else l
cl l=map(c(length$last l))l
pt n=cl$take n fp
Without formatting, 52C:
i l=zipWith(+)(0:l)$l++[0]
pt n=take n$iterate i[1]
A more readable form of it:
iterateStep row = zipWith (+) (0:row) (row++[0])
pascalsTriangle n = take n $ iterate iterateStep [1]
-- For the formatted version, we reduce the number of rows at the final step:
formatRow r = concatMap (\l -> ' ':(show l)) r
formattedLines = map formatRow $ iterate iterateStep [1]
centerTo width line =
if length line < width
then centerTo width (" " ++ line ++ " ")
else line
centerLines lines = map (centerTo (length $ last lines)) lines
pascalsTriangle n = centerLines $ take n formattedLines
And perl, 111C, no centering:
$n=<>;$p=' 1 ';for(1..$n){print"$p\n";$x=" ";while($p=~s/^(?= ?\d)(\d* ?)(\d* ?)/$2/){$x.=($1+$2)." ";}$p=$x;}
Scheme — compressed version of 100 characters
(define(P h)(define(l i r)(if(> i h)'()(cons r(l(1+ i)(map +(cons 0 r)(append r '(0))))))(l 1 '(1)))
This is it in a more readable form (269 characters):
(define (pascal height)
(define (next-row row)
(map +
(cons 0 row)
(append row '(0))))
(define (iter i row)
(if (> i height)
'()
(cons row
(iter (1+ i)
(next-row row)))))
(iter 1 '(1)))
VBA/VB6 (392 chars w/ formatting)
Public Function PascalsTriangle(ByVal pRows As Integer)
Dim iRow As Integer
Dim iCol As Integer
Dim lValue As Long
Dim sLine As String
For iRow = 1 To pRows
sLine = ""
For iCol = 1 To iRow
If iCol = 1 Then
lValue = 1
Else
lValue = lValue * (iRow - iCol + 1) / (iCol - 1)
End If
sLine = sLine & " " & lValue
Next
Debug.Print sLine
Next
End Function
PHP 100 characters
$v[]=1;while($a<34){echo join(" ",$v)."\n";$a++;for($k=0;$k<=$a;$k++)$t[$k]=$v[$k-1]+$v[$k];$v=$t;}
Ruby, 83c:
def p(n);n>0?(m=p(n-1);k=m.last;m+[([0]+k).zip(k+[0]).map{|x|x[0]+x[1]}]):[[1]];end
test:
irb(main):001:0> def p(n);n>0?(m=p(n-1);k=m.last;m+[([0]+k).zip(k+[0]).map{|x|x[0]+x[1]}]):[[1]];end
=> nil
irb(main):002:0> p(5)
=> [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]
irb(main):003:0>
Another python solution, that could be much shorter if the builtin functions had shorter names... 106 characters.
from itertools import*
r=range
p=lambda n:[[len(list(combinations(r(i),j)))for j in r(i+1)]for i in r(n)]
Another try, in prolog (I'm practising xD), not too short, just 164c:
s([],[],[]).
s([H|T],[J|U],[K|V]):-s(T,U,V),K is H+J.
l([1],0).
l(P,N):-M is N-1,l(A,M),append(A,[0],B),s(B,[0|A],P).
p([],-1).
p([H|T],N):-M is N-1,l(H,N),p(T,M).
explanation:
s = sum lists element by element
l = the Nth row of the triangle
p = the whole triangle of size N
VBA, 122 chars:
Sub p(n)
For r = 1 To n
l = "1"
v = 1
For c = 1 To r - 1
v = v / c * (r - c)
l = l & " " & v
Next
Debug.Print l
Next
End Sub
I wrote this C++ version a few years ago:
#include <iostream>
int main(int,char**a){for(int b=0,c=0,d=0,e=0,f=0,g=0,h=0,i=0;b<atoi(a[1]);(d|f|h)>1?e*=d>1?--d:1,g*=f>1?--f:1,i*=h>1?--h:1:((std::cout<<(i*g?e/(i*g):1)<<" "?d=b+=c++==b?c=0,std::cout<<std::endl?1:0:0,h=d-(f=c):0),e=d,g=f,i=h));}
The following is just a Scala function returning a List[List[Int]]. No pretty printing or anything. Any suggested improvements? (I know it's inefficient, but that's not the main challenge now, is it?). 145 C.
def p(n: Int)={def h(n:Int):List[Int]=n match{case 1=>1::Nil;case _=>(0::h(n-1) zipAll(h(n-1),0,0)).map{n=>n._1+n._2}};(1 to n).toList.map(h(_))}
Or perhaps:
def pascal(n: Int) = {
def helper(n: Int): List[Int] = n match {
case 1 => 1 :: List()
case _ => (0 :: helper(n-1) zipAll (helper(n-1),0,0)).map{ n => n._1 + n._2 }
}
(1 to n).toList.map(helper(_))
}
(I'm a Scala noob, so please be nice to me :D )
a Perl version (139 chars w/o shebang)
#p = (1,1);
while ($#p < 20) {
#q =();
$z = 0;
push #p, 0;
foreach (#p) {
push #q, $_+$z;
$z = $_
}
#p = #q;
print "#p\n";
}
output starts from 1 2 1
PHP, 115 chars
$t[][]=1;
for($i=1;$i<$n;++$i){
$t[$i][0]=1;
for($j=1;$j<$i;++$j)$t[$i][$j]=$t[$i-1][$j-1]+$t[$i-1][$j];
$t[$i][$i]=1;}
If you don't care whether print_r() displays the output array in the correct order, you can shave it to 113 chars like
$t[][]=1;
for($i=1;$i<$n;++$i){
$t[$i][0]=$t[$i][$i]=1;
for($j=1;$j<$i;++$j)$t[$i][$j]=$t[$i-1][$j-1]+$t[$i-1][$j];}
Perl, 63 characters:
for(0..9){push#z,1;say"#z";#z=(1,map{$z[$_-1]+$z[$_]}(1..$#z))}
My attempt in C++ (378c). Not anywhere near as good as the rest of the posts.. but I'm proud of myself for coming up with a solution on my own =)
int* pt(int n)
{
int s=n*(n+1)/2;
int* t=new int[s];
for(int i=0;i<n;++i)
for(int j=0;j<=i;++j)
t[i*n+j] = (!j || j==i) ? 1 : t[(i-1)*n+(j-1)] + t[(i-1)*n+j];
return t;
}
int main()
{
int n,*t;
std::cin>>n;
t=pt(n);
for(int i=0;i<n;++i)
{
for(int j=0;j<=i;j++)
std::cout<<t[i*n+j]<<' ';
std::cout<<"\n";
}
}
Old thread, but I wrote this in response to a challenge on another forum today:
def pascals_triangle(n):
x=[[1]]
for i in range(n-1):
x.append([sum(i) for i in zip([0]+x[-1],x[-1]+[0])])
return x
for x in pascals_triangle(5):
print('{0:^16}'.format(x))
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]

Resources