Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
/*********************************************************************
ASSIGNMENT NO : A-1
TITLE : 1. Using Divide and Conquer Strategies design a cluster/Grid
of BBB or Raspberry pi or Computers in network to run a
function for Binary Search Tree using C /C++/ Java/Python/
Scala NAME : ROLL NO CLASS : BE COMPUTER BATCH : B-3
********************************************************************/
A1.py
class BST(object):
def init (self):
self.root = None
def insert(self, t):
new = BSTnode(t)
if self.root is None:
self.root = new
else:
node = self.root
while True:
if t < node.key:
# Go left
if node.left is None:
node.left = new
new.parent = node
break
node = node.left
else:
# Go right
if node.right is None:
node.right = new
new.parent = node
break
node = node.right
return new
def find(self, t):
node = self.root
while node is not None:
if t == node.key:
return node
elif t < node.key:
node = node.left
else:
node = node.right
return None
def delete_min(self):
if self.root is None:
return None, None
else:
# Walk to leftmost node.
node = self.root
while node.left is not None:
node = node.left
# Remove that node and promote its right subtree.
if node.parent is not None:
node.parent.left = node.right
else: # The root was smallest.
self.root = node.right
if node.right is not None:
node.right.parent = node.parent
parent = node.parent
node.disconnect()
return node, parent
def str (self):
if self.root is None: return '<empty tree>'
def recurse(node):
if node is None: return [], 0, 0
label = str(node.key)
left_lines, left_pos, left_width = recurse(node.left)
right_lines, right_pos, right_width = recurse(node.right)
middle = max(right_pos + left_width - left_pos + 1, len(label), 2)
pos = left_pos + middle // 2
width = left_pos + middle + right_width - right_pos
while len(left_lines) < len(right_lines):
left_lines.append(' ' * left_width)
while len(right_lines) < len(left_lines):
right_lines.append(' ' * right_width)
if (middle - len(label)) % 2 == 1 and node.parent is not None and \
node is node.parent.left and len(label) < middle:
label += '.'
label = label.center(middle, '.')
if label[0] == '.': label = ' ' + label[1:]
if label[-1] == '.': label = label[:-1] + ' ' lines = [' ' * left_pos + label + ' ' * (right_width - right_pos),
' ' * left_pos + '/' + ' ' * (middle-2) +
'\\' + ' ' * (right_width - right_pos)] + \
[left_line + ' ' * (width - left_width - right_width) +
right_line
for left_line, right_line in zip(left_lines, right_lines)]
return lines, pos, width
return '\n'.join(recurse(self.root) [0])
class BSTnode(object):
def init (self, t):
self.key = t
self.disconnect()
def disconnect(self):
self.left = None
self.right = None
self.parent = None
def test(args=None, BSTtype=BST):
import random, sys
if not args: args = sys.argv[1:]
if not args:
print ('usage: %s <number-of-random-items | item item
item ...>' %sys.argv[0])
sys.exit()
elif len(args) == 1: items = (random.randrange(100) for i in range(int(args[0])))
else:
items = [int(i) for i in args]
tree = BSTtype()
print (tree) for item in items:
tree.insert(item)
print (tree)
if name == '__main ': test()
”””
**********************************Output*****************************
aman@aman-Inspiron-5520:~$ cd Desktop/410454\ Computer\
Laboratory-IV/
aman@aman-Inspiron-5520:~/Desktop/410454 Computer Laboratory-
IV$ sudo python A1.py
usage: A1.py <number-of-random-items | item item item ...>
aman@aman-Inspiron-5520:~/Desktop/410454 Computer Laboratory-
IV$ sudo python A1.py 4 <empty tree> 74
/\
74
/\
74
/\
74
/ \
26 74
/\ /\
74
/ \
26 74
/\ /\
70
/\
aman@aman-Inspiron-5520:~/Desktop/410454 Computer Laboratory-IV$
”””
/*********************************************************************
ASSIGNMENT NO : A-2
TITLE : 2. Using Divide and Conquer Strategies design a class for
Concurrent Quick Sort using C++.
NAME : ROLL NO :
CLASS : BE COMPUTER BATCH : B-3
********************************************************************/
A2.cpp #include<iostream>
#include<iostream>
#include<stdio.h>
#include<stdlib.h> #include<pthread.h>
using namespace std;
struct array
{ int *arr;
int first;
int last;
};
int n;
void* quick(void *in)
{ array* a=(array*)in;
int i,j;
pthread_t id=pthread_self();
if(a->first < a->last)
{ int temp=0;
int i=a->first;
int j=a->last;
int pivot=a->arr[a->first];
while(i<j)
{
while(a->arr[i] <=pivot && i<j)
i++;
while(a->arr[j] > pivot && i<=j)
j--;
if(i<=j)
{
temp=a->arr[i]; a->arr[i]=a->arr[j];
a->arr[j]=temp;
}
}
temp=a->arr[j]; a->arr[j]=a->arr[a->first];
a->arr[a->first]=temp;
pthread_t threads[2]; cout<<"Thread ID: "<<id<<" for pivot: "<<pivot<<endl;
array a1,a2;
a1.arr=new int[n];
a2.arr=new int[n];
a1.arr=a->arr;
a2.arr=a->arr;
a1.first=a->first;
a1.last=j-1;
a2.first=j+1;
a2.last=a->last;
pthread_create(&threads[0],NULL,&quick,(void *)&a1);
pthread_create(&threads[1],NULL,&quick,(void *)&a2);
pthread_join(threads[0],NULL);
pthread_join(threads[1],NULL);
}
} int main()
{
array a1;
int n,i;
cout<<"Enter size of array: ";
cin>>n;
a1.arr=new int[n];
a1.first=0;
a1.last=n-1;
cout<<"Enter elements:"<<endl;
for(i=0;i<n;i++)
cin>>a1.arr[i];
quick(&a1);
cout<<"Sorted array is:"<<endl;
for(i=0;i<n;i++)
cout<<a1.arr[i]<<" ";
cout<<endl;
return 0;
}
/*
**********************************Output*****************************
aman@aman-Inspiron-5520:~$ cd Desktop/410454\ Computer\
Laboratory-IV/
aman@aman-Inspiron-5520:~/Desktop/410454 Computer Laboratory-
IV$ g++ A2.cpp –pthread
aman@aman-Inspiron-5520:~/Desktop/410454 Computer Laboratory-
IV$ ./a.out
Enter size of array: 5
Enter elements:
21
23
65
12
9
Thread ID: 3073894144 for pivot: 21
Thread ID: 3073887040 for pivot: 12
Thread ID: 3065494336 for pivot: 65
Sorted array is:
9 12 21 23 65
aman@aman-Inspiron-5520:~/Desktop/410454 Computer Laboratory-IV$
*/
/*********************************************************************
ASSIGNMENT NO : A-3
TITLE : 3. Write a MPI program for calculating a quantity called
coverage from data files.
Hint :- Program distributes computation efficiently across the
cluster. The program should be able to work with any number of
nodes and should yield the same results as the serial code. NAME : ROLL NO :
CLASS : BE COMPUTER BATCH : B-3
********************************************************************/
A3.cpp
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#define v 1 /* verbose flag, output if 1, no output if 0 */
#define tag 100 /* tag for sending a number */
int main ( int argc, char *argv[] )
{
int p,myid,i,f,*x;
double start, end;
MPI_Status status;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&p);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
if(myid == 0) /* the manager allocates and initializes x */
{
x = (int*)calloc(p,sizeof(int));
x[0] = 50;
for (i=1; i<p; i++) x[i] = 2*x[i-1];
if(v>0)
{
printf("The data to square : ");
for (i=0; i<p; i++)
printf(" %d",x[i]);
printf("\n");
}
}
if(myid == 0) /* the manager copies x[0] to f */
{ /* and sends the i-th element to the i-th processor */
f = x[0];
for(i=1; i<p; i++)
MPI_Send(&x[i],1,MPI_INT,i,tag,MPI_COMM_WORLD);
}
else /* every worker receives its f from root */
{
MPI_Recv(&f,1,MPI_INT,0,tag,MPI_COMM_WORLD,&status);
if(v>0)
printf("Node %d will square %d\n",myid,f);
}
start = MPI_Wtime();
f *= f; /* every node does the squaring */
if(myid == 0) /* the manager receives f in x[i] from processor i */
for(i=1; i<p; i++)
MPI_Recv(&x[i],1,MPI_INT,i,tag,MPI_COMM_WORLD,&status);
else /* every worker sends f to the manager */
MPI_Send(&f,1,MPI_INT,0,tag,MPI_COMM_WORLD);
if(myid == 0) /* the manager prints results */
{
x[0] = f;
printf("The squared numbers : ");
for(i=0; i<p; i++)
printf(" %d",x[i]);
printf("\n");
end = MPI_Wtime();
printf("Runtime = %f\n", end-start);
}
MPI_Finalize();
return 0;
}
/*
**********************************Output*****************************
aman@aman-Inspiron-5520:~$ cd openmpi/ openmpi-1.10.2/ examples/
aman@aman-Inspiron-5520:~/openmpi/openmpi-1.10.2/examples$ mpicc A3.c -o A3
aman@aman-Inspiron-5520:~/openmpi/openmpi-1.10.2/examples$ mpirun -np
2 ./A3
The data to square : 50 100
The squared numbers : 2500 10000
Runtime = 0.000311
Node 1 will square 100
aman@aman-Inspiron-5520:~/openmpi/openmpi-1.10.2/examples$
*/
/*********************************************************************
ASSIGNMENT NO : A-4
TITLE : 4. Write a program on an unloaded cluster for several different
numbers of nodes and record the time taken in each case. Draw
a graph of execution time against the number of nodes.
NAME : ROLL NO :
CLASS : BE COMPUTER BATCH : B-3
********************************************************************/
A4.c
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#define v 1 /* verbose flag, output if 1, no output if 0 */
int main ( int argc, char *argv[] )
{
int myid,j,*data,tosum[25],sums[4];
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
if(myid==0) /* manager allocates and initializes the data */
{
data = (int*)calloc(100,sizeof(int));
for (j=0; j<100; j++) data[j] = j+1;
if(v>0)
{
printf("The data to sum : ");
for (j=0; j<100; j++)
printf(" %d",data[j]);
printf("\n");
}
}
MPI_Scatter(data,25,MPI_INT,tosum,25,MPI_INT,0,MPI_COMM_WORLD);
if(v>0) /* after the scatter, every node has 25 numbers to sum*/
{
printf("Node %d has numbers to sum :",myid);
for(j=0; j<25; j++) printf(" %d", tosum[j]);
printf("\n");
}
sums[myid] = 0;
for(j=0; j<25; j++) sums[myid] += tosum[j];
if(v>0) printf("Node %d computes the sum %d\n",myid,sums[
myid]);
MPI_Gather(&sums[myid],1,MPI_INT,sums,1,MPI_INT,0,MPI_COMM_WORLD);
if(myid==0) /* after the gather, sums contains the four sums*/
{
printf("The four sums : ");
printf("%d",sums[0]);
for(j=1; j<4; j++) printf(" + %d", sums[j]);
for(j=1; j<4; j++) sums[0] += sums[j];
printf(" = %d, which should be 5050.\n",sums[0]);
}
MPI_Finalize();
return 0;
}
/*
**********************************Output*****************************
aman@aman-Inspiron-5520:~$ cd openmpi/ openmpi-1.10.2/ examples/
aman@aman-Inspiron-5520:~/openmpi/openmpi-1.10.2/examples$ mpicc A4.c -o A4
aman@aman-Inspiron-5520:~/openmpi/openmpi-1.10.2/examples$ mpirun -np
4 ./A4
The data to sum : 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
Node 0 has numbers to sum : 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
Node 0 computes the sum 325
Node 1 has numbers to sum : 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
Node 1 computes the sum 950
Node 3 has numbers to sum : 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
Node 3 computes the sum 2200
Node 2 has numbers to sum : 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
Node 2 computes the sum 1575
The four sums : 325 + 950 + 1575 + 2200 = 5050, which should be 5050.
aman@aman-Inspiron-5520:~/openmpi/openmpi-1.10.2/examples$
*/
/*********************************************************************
ASSIGNMENT NO : A-5
TITLE : 5. build a small compute cluster using Raspberry Pi/BBB
modules to implement Booths Multiplication algorithm.
NAME : ROLL NO :
CLASS : BE COMPUTER BATCH : B-3
********************************************************************/
server_booth.py
# take values A,S from clients and run the main loop for calculating P
#TODO- change the code for accomodating different sequence of exec(client2 rus
before client1)
import socket
def addition(op1, op2):
# length of P and A and S is same.
result=""
carry="0"
for i in range(len(op1)-1, -1, -1): #run reverse loop
if op1[i]=="1" and op2[i]=="1":
if carry=="1":
result="1"+result
carry="1"
else: #carry = 0
result="0"+result
carry="1"
elif op1[i]=="0" and op2[i]=="0":
if carry=="1":
result="1"+result
carry="0"
else: #carry = 0
result="0"+result
carry="0"
elif op1[i]=="0" and op2[i]=="1":
if carry=="1":
result="0"+result
carry="1"
else: #carry = 0
result="1"+result
carry="0"
else: # 1, 0
if carry=="1":
result="0"+result
carry="1"
else: #carry = 0
result="1"+result
carry="0"
return result
s = socket.socket() # Create a socket object
s.bind(("192.168.1.114", 80)) # Bind to the port
M=int(input("Enter a multiplicant:"))
R=int(input("Enter a multiplier:"))
M, R=bin(M), bin(R)
print "Binary representation: ", M, R
s.listen(2) # Now wait for client connection.
client, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
client2, addr2 = s.accept()
print 'Got connection from', addr2
'''
Send the value of both. Client will return A, S. It will also return length_R as first
param. <Length_R>A<A>S<S>
Send the value of length of R and value of R. Client will return P. P<P>
'''
client.send(M+" "+R)
AS=client.recv(1024) # recv A, S
index_A=AS.index("A")
index_S=AS.index("S")
A=AS[index_A+1:index_S]
S=AS[index_S+1:]
length_R=int(AS[:index_A])
client2.send(str(length_R)+" "+R)
P=client2.recv(1024) # recv P
index_P=P.index("P")
P=P[index_P+1:]
P_length=len(P)
#we've got A,S,P in strings
for i in range(length_R):
last_two_digits=P[P_length-2:P_length]
if last_two_digits == "01":
#add A in P and store that in P and ignore overflows
P=addition(A, P)
elif last_two_digits == "10":
#add S in P aND store the result in P and IGNORE OVerflows
P=addition(S, P)
#print "After addn", P
#arithmetic right shift (copy the sign bit as well). Start looping from the right
most digits
P=P[0]+P[0:P_length-1]
P=P[:P_length-1]
print P
client_multiplicand.py
# calculate values A, S and send it back to server.
import socket
def twos_comp(binM):
S = [int(x) for x in binM]
flag = 0
for i in range(len(S)-1, -1, -1):
if flag==1:
#invert
if S[i]==1:
S[i]=0
else:
S[i]=1
continue
if S[i]==1:
flag=1
return S
s = socket.socket() # Create a socket object
s.connect(("192.168.1.114", 80))
temp=s.recv(1024)
temp=temp.split()
M, R=temp[0], temp[1]
origM, origR="", ""
Max_length=0
flag,flag_R=0,0 # flag=1: -M, flag=2: M. flag_R=1: -R,
flag_R=2: R
if M[0]=="-":
M=M[3:]
origM=M
M=twos_comp(M)
M=[str(x) for x in M]
M=''.join(M)
flag=1
else:
M=M[2:]
flag=2
if R[0]=="-":
R=R[3:]
origR=R
R=twos_comp(R)
R=[str(x) for x in R]
R=''.join(R)
flag_R=1
else:
R=R[2:]
flag_R=2
if len(M)>= len(R):
padding=len(M)-len(R)+1 #+1 for sign bit
if flag==1:
M="1"+M
else:
M="0"+M
for i in range (padding):
if flag_R==1:
R="1"+R
else:
R="0"+R
else:
Max_length=len(M)
padding=len(R)-len(M)+1
if flag_R==1:
R="1"+R
else:
R="0"+R
for i in range (padding):
if flag==1:
M="1"+M
else:
M="0"+M
Max_length=len(R)
print M, R
#now calc A, S using the length of M and R and 1 (lenM+lenR+1)
A = []
for i in range(len(M)+len(R)+1):
A.append(0)
for i in range(len(M)):
A[i]=int(M[i])
A=[str(x) for x in A]
print "A: ", A
#A is ready at this point
if flag==1: # orignal M was -ve. So we need origM with the minus
sign eliinated
for i in range(Max_length-len(origM)):
origM="0"+origM
S=[str(x) for x in origM]
else:
S=twos_comp(M)
for i in range(len(M)+len(R)+1-len(S)):
S.append(0)
S=[str(x) for x in S]
#S is ready at this point
print "S: ", S
#pack the A ans S in a buffer string
Send_AS= str(len(R))+"A"+''.join(A) #secret- length of both operands is
same. So u can replace R with M
Send_AS += "S"+''.join(S)
print Send_AS
#send the A and S to server and the job here is done
s.send(Send_AS)
client_multiplier.py
# calculate value P and send it back to server.
import socket
def twos_comp(binM):
S = [int(x) for x in binM]
flag = 0
for i in range(len(S)-1, -1, -1):
if flag==1:
#invert
if S[i]==1:
S[i]=0
else:
S[i]=1
continue
if S[i]==1:
flag=1
return S
s = socket.socket() # Create a socket object
s.connect(("192.168.1.114", 80))
temp=s.recv(1024)
temp=temp.split()
length_R, R= int(temp[0]), temp[1]
if R[0]=="-":
R=R[3:] #origR=R
R=twos_comp(R)
R=[str(x) for x in R]
R=''.join(R)
for i in range (length_R-len(R)):
R="1"+R
else:
R=R[2:] for i in range (length_R-len(R)):
R="0"+R
#flag_R=2
P = []
for i in range(2*length_R + 1):
P.append(0)
print "check length of P: ", P
for i in range(len(R)):
P[length_R+i]=int(R[i])
P=[str (x) for x in P]
P="".join(P)
print P
s.send("P"+P)
”””
**********************************Output*****************************
Output:- server_booth.py aman@aman-Inspiron-5520:~$ sudo su
[sudo] password for aman:
root@aman-Inspiron-5520:/home/aman# python server_booth.py
Enter a multiplicant:3
Enter a multiplier:4
Binary representation: 0b11 0b100
Got connection from ('192.168.1.113', 45472)
Got connection from ('192.168.1.112', 58905)
00001100
root@aman-Inspiron-5520:/home/aman#
Output:- client_multiplicand.py
aman@aman-Inspiron-5520:~$ sudo su
[sudo] password for aman:
root@aman-Inspiron-5520:/home/aman# python client_multiplicand.py
0011 0100
A: ['0', '0', '1', '1', '0', '0', '0', '0', '0']
S: ['1', '1', '0', '1', '0', '0', '0', '0', '0']
4A001100000S110100000
root@aman-Inspiron-5520:/home/aman#
Output:- client_multiplier.py
aman@aman-Inspiron-5520:~$ sudo su
[sudo] password for aman:
root@aman-Inspiron-5520:/home/aman# python client_multiplier.py
check length of P: [0, 0, 0, 0, 0, 0, 0, 0, 0]
000001000
root@aman-Inspiron-5520:/home/aman#
”””
/*********************************************************************
ASSIGNMENT NO : A-6
TITLE : Elective-IV A. Use Business intelligence and analytics tools to
recommend the combination of share purchases and sales for
maximizing the profit.
NAME : ROLL NO : CLASS : BE COMPUTER BATCH : B-3
********************************************************************/
/*********************************************************************
ASSIGNMENT NO : A-7
TITLE : Elective-IV C. Write a mobile application to generate a
Scientific calculator using J2ME/ Python/ Scala/ C++/Android.
NAME : ROLL NO :
CLASS : BE COMPUTER BATCH : B-3
********************************************************************/
A7.py
# -*- coding: utf-8 -*-
import math
import random
import sys
pi = math.pi
last = 1
ask = raw_input("Please enter an operation ")
while True:
while ask == "Please enter an operation ":
ask = raw_input("Please enter an operation ")
if ask == "add":
a = input ("First number ")
print a
b = input ("Second number ")
print b
last = a + b
print last
ask = raw_input ("Please enter an operation ")
elif ask == "subtract":
a = input ("First number ")
print a
b = input ("Second number ")
print b
last = a - b
print last
ask = raw_input ("Please enter an operation ")
elif ask == "multiply":
a = input ("First number ")
print a
b = input ("Second number ")
print b
last = a * b
print last
ask = raw_input ("Please enter an operation ")
elif ask == "divide":
a = input ("First number ")
print a
b = input ("Second number ")
print b
last = a / b
print last
ask = raw_input ("Please enter an operation ")
elif ask == "math.sqrt":
a = input ("Number ")
print a
last = math.sqrt(a)
print last
ask = raw_input ("Please enter an operation ")
elif ask == "power":
a = input ("Base ")
print a
b = input ("Exponent ")
print b
last = a ^ b
print last
ask = raw_input ("Please enter an operation ")
elif ask == "list":
a = input ("Low range ")
print a
b = input ("High range ")
print b
c = input ("Count by ")
print c
last = range(a, b, c)
print last
ask = raw_input ("Please enter an operation ")
elif ask == "factorial":
a = input ("Number ")
print a
last = math.factorial(a)
ask = raw_input ("Please enter an operation ")
elif ask == "random":
a = raw_input ("Low number ")
a = float(a)
print a
b = raw_input ("High number ")
b = float(b)
print b
last = random.randint(a, b)
print last
ask = raw_input ("Please enter an operation ")
elif ask == "features":
print "Stable features:\n-Addition\n-Subtraction\n-Multiplication\n-
Division\n-Square Root\n-Powers\n-Factorials\n-Random number
generator\n\nFeatures in development:\n-Prime number finding (using the sieve of
eratosthenes)\n\n\n Also type 'help' to see all of the commands"
ask = raw_input ("Please enter an operation ")
elif ask == "var":
print "Variables: \n pi \n last (last answer)"
ask = raw_input ("Please enter an operation ")
elif ask == "help":
print "add - adds two numbers \nsubtract - subtracts two
numbers\nmultiply - multiplys two numbers together\ndivide - divides two
numbers\nsqrt - finds the square root of two numbers\npower - finds the power of a
number according to input\nlist - asks for a low and high number, then lists all of the
numbers in between, counting by the specified number\nfactorial - multiplys a
number counting down, e.g. n! = n * n-1 * n-2 and so on\nrandom - outputs a random
number with the specified range"
ask = raw_input ("Please enter an operation ")
elif ask == "exit":
sys.exit()
ask = raw_input ("Please enter an operation ")
else:
operations")
print("No valid operation. Please use 'help' to find all of the valid
ask = raw_input ("Please enter an operation ")
”””
**********************************Output*****************************
aman@aman-Inspiron-5520:~$ cd Desktop/410454\ Computer\ Laboratory-IV/
aman@aman-Inspiron-5520:~/Desktop/410454 Computer Laboratory-IV$ python
A7.py
Please enter an operation add
First number 5
5
Second number 5
5
10
Please enter an operation subtract
First number 5
5
Second number 2
2
3
Please enter an operation multiply
First number 5
5
Second number 4
4
20
Please enter an operation divide
First number 50
50
Second number 10
10
5
Please enter an operation math.sqrt
Number 5
5
2.2360679775
Please enter an operation exit
aman@aman-Inspiron-5520:~/Desktop/410454 Computer Laboratory-IV$
”””
/*********************************************************************
ASSIGNMENT NO : B-1
TITLE : 1. 8-Queens Matrix is Stored using JSON/XML having first
Queen placed, use back-tracking to place remaining Queens to
generate final 8-queen’s Matrix using Python. Create a
backtracking scenario and use HPC architecture (Preferably
BBB) for computation of next placement of a queen.
NAME : ROLL NO :
CLASS : BE COMPUTER BATCH : B-3
********************************************************************/
B1.py
import json
def isattack(board,r,c):
for i in range(r):
if(board[i][c]==1):
return True
i=r-1
j=c-1
while((i>=0) and (j>=0)):
if(board[i][j]==1):
return True
i=i-1
j=j-1
i=r-1
j=c+1
while((i>=0) and (j<8)):
if(board[i][j]==1):
return True
i=i-1
j=j+1
return False
def solve(board,row):
i=0
while(i<8):
if(not isattack(board, row, i)):
board[row][i]=1
if(row==7):
return True
else:
if(solve(board, row+1)):
return True
else:
board[row][i]=0
i=i+1
if(i==8):
return False
def printboard(board):
for i in range(8):
for j in range(8):
print str(board[i][j])+" ",
print "\n"
board = [[0 for x in range(8)] for x in range(8)]
if name == '__main ':
data=[]
with open('b1.json') as f:
data=json.load(f)
if(data["start"]<0 or data["start"]>7):
print "Invalid JSON input"
exit()
board[0][data["start"]]=1
if(solve(board, 1)):
print "Queens problem solved!!!"
print "Board Configuration:"
printboard(board)
else:
print "Queens problem not solved!!!"
”””
b1.json
{"start":3}
”””
”””
**********************************Output*****************************
aman@aman-Inspiron-5520:~$ sudo su
[sudo] password for aman:
root@aman-Inspiron-5520:/home/aman# ssh 192.168.7.2
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS
CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle
attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ECDSA key sent by the remote host is
40:69:fa:bb:3f:36:81:62:b7:a3:92:7d:d7:08:30:94.
Please contact your system administrator.
Add correct host key in /home/sl171/.ssh/known_hosts to get rid of this
message.
Offending ECDSA key in /home/sl171/.ssh/known_hosts:1
remove with: ssh-keygen -f "/home/sl171/.ssh/known_hosts" -R
192.168.7.2
ECDSA host key for 192.168.7.2 has changed and you have requested
strict checking.
Host key verification failed.
aman@aman-Inspiron-5520:~$ ssh-keygen -f
"/home/aman/.ssh/known_hosts" -R 192.168.7.2
# Host 192.168.7.2 found: line 1 type ECDSA
/home/aman/.ssh/known_hosts updated.
Original contents retained as /home/aman/.ssh/known_hosts.old
aman@aman-Inspiron-5520:~$ssh [email protected]
The authenticity of host '192.168.7.2 (192.168.7.2)' can't be established.
ECDSA key fingerprint is
40:69:fa:bb:3f:36:81:62:b7:a3:92:7d:d7:08:30:94.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.7.2' (ECDSA) to the list of known
hosts.
Debian GNU/Linux 7
BeagleBoard.org Debian Image 2015-03-01
Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian
default username:password is [debian:temppwd]
Last login: Sun Mar 1 20:48:06 2017 from aman@aman-Inspiron-5520:~$
root@beaglebone:~# cd ..
root@beaglebone:/# ls
bin boot dev etc export home lib lost+found media mnt
opt proc root run sbin selinux srv sys tmp usr var
root@beaglebone:/# cd media
root@beaglebone:/media# ls
BEAGLEBONE BEAGLEBONE_
root@beaglebone:/media# cd BEAGLEBONE_
root@beaglebone:/media# python B1.py
Queens problem solved!!!
Board Configuration:
0 0 0 1 0 0 0 0
1
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0 0 0 0 0 0 0 1
0
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
root@beaglebone:/media#
Broadcast message from root@beaglebone (Sun Mar 1 20:53:24 2017):
Power button pressed
The system is going down for system halt NOW!
Connection to 192.168.7.2 closed by remote host.
Connection to 192.168.7.2 closed.
aman@aman-Inspiron-5520:~$
”””
/*********************************************************************
ASSIGNMENT NO : B-4
TITLE : 4. Write a program to check task distribution using Gprof.l
NAME : ROLL NO :
CLASS : BE COMPUTER BATCH : B-3
********************************************************************/
qs.cpp
#include <iostream>
#include <vector>
using namespace std;
/**
* Partition the elements of 1st (A), such that first have elements smaller
than
* "who", followed by elements larger than "who". Return the last position
of an
* element smaller or equal to "who".
*/
int partition(vector<int>& A, int left, int right, int who) {
for (int i=left; i<right; ++i) {
if (A[i] <= who) {
swap(A[i], A[left]);
left ++;
}
}
return left - 1;
}
/**
* Quick sort vector A, between index "left" and index "right".
*/
void qsort(vector<int>& A, int left, int right) {
if (left >= right) return;
int middle = left + (right - left) / 2; //find out middle element
swap(A[middle], A[left]);
int midpoint = partition(A, left + 1, right, A[left]);
swap(A[left], A[midpoint]);
qsort(A, left, midpoint);
qsort(A, midpoint + 1, right);
}
void printVector(vector<int>& A) {
for (int i=0; i<A.size(); ++i) {
cout << A[i] << " ";
}
cout << endl;
}
void testPartition() {
int elements[] = {1, 3, 1, 1, 3};
vector<int> A(elements, elements + 5);
int n = partition(A, 0, 5, 1);
cout << n << endl;
printVector(A);
}
void testSort() {
int elements[] = {1, 12,5, 2,7, 6, 20, 25};
vector<int> A(elements, elements + 8);
qsort(A, 0, A.size());
printVector(A);
}
int main ()
{
testPartition();
cout << "---------------" << endl;
testSort();
return 0;
}
/*
**********************************Output*****************************
aman@aman-Inspiron-5520:~$ cd Desktop/410454\ Computer\
Laboratory-IV/
aman@aman-Inspiron-5520:~/Desktop/410454 Computer Laboratory-
IV$ gedit qs.cpp
aman@aman-Inspiron-5520:~/Desktop/410454 Computer Laboratory-
IV$ g++ qs.cpp -pg -o test
aman@aman-Inspiron-5520:~/Desktop/410454 Computer Laboratory-
IV$ ./test
2
1 1 1 3 3
---------------
1 2 5 6 7 12 20 25
aman@aman-Inspiron-5520:~/Desktop/410454 Computer Laboratory-
IV$ gprof test gmon.out -p
Flat profile:
Each sample counts as 0.01 seconds.
no time accumulated
% cumulative self self total
time seconds seconds calls Ts/call Ts/call name
0.00 0.00 0.00 89 0.00 0.00 std::vector<int, std::allocator<int> >::operator[](unsigned long)
0.00 0.00 0.00 25 0.00 0.00 void std::swap<int>(int&, int&)
0.00 0.00 0.00 16 0.00 0.00 std::vector<int, std::allocator<int> >::size() const
0.00 0.00 0.00 10 0.00 0.00 std::_Iter_base<int*, false>::_S_base(int*)
0.00 0.00 0.00 9 0.00 0.00 partition(std::vector<int, std::allocator<int> >&, int, int, int)
0.00 0.00 0.00
std:: niter_base<int*>
6
(int*)
0.00 0.00 std::_Niter_base<int*>::iterator_type
0.00
0.00
0.00
4
0.00
0.00
gnu_cxx::new_allocator<int>::~new_allocator()
0.00 0.00 0.00 4 0.00 0.00 std::allocator<int>::~allocator()
0.00 0.00 0.00 4 0.00 0.00 std::_Vector_base<int,
std::allocator<int> >::_M_get_Tp_allocator()
0.00 0.00 0.00 4 0.00 0.00 std::_Miter_base<int*>::iterator_type
std:: miter_base<int*>(int*)
0.00 0.00 0.00 2 0.00 0.00 printVector(std::vector<int, std::allocator<int> >&)
0.00 0.00 0.00 2 0.00 0.00 gnu_cxx::new_allocator<int>::deallocate(int*, unsigned long)
0.00 0.00 0.00 2 0.00 0.00 gnu_cxx::new_allocator<int>::allocate(unsigned long, void
const*)
0.00 0.00 0.00 2 0.00 0.00
gnu_cxx::new_allocator<int>::new_allocator( gnu_cxx::new_allocator<int> const&)
0.00 0.00 0.00 2 0.00 0.00 gnu_cxx::new_allocator<int>::new_allocator()
0.00 0.00 0.00 2 0.00 0.00 gnu_cxx::new_allocator<int>::max_size() const
0.00 0.00 0.00 2 0.00 0.00 std::allocator<int>::allocator(std::allocator<int> const&)
0.00 0.00 0.00 2 0.00 0.00 std::allocator<int>::allocator()
0.00 0.00 0.00 2 0.00 0.00 int* std:: copy_move<false,
true,std::random_access_iterator_tag>:: copy_m<int>(int const*, int const*, int*)
0.00 0.00 0.00 2 0.00 0.00 void std::_Destroy_aux<true>:: destroy<int*>(int*, int*)
0.00 0.00 0.00 2 0.00 0.00
std::_Vector_base<int,std::allocator<int> >::_M_allocate(unsigned long)
0.00 0.00 0.00 2 0.00 0.00
std::_Vector_base<int,std::allocator<int> >::_Vector_impl::_Vector_impl(std::allocator<int> const&)
0.00 0.00 0.00 2 0.00 0.00
std::_Vector_base<int,std::allocator<int> >::_Vector_impl::~_Vector_impl()
0.00 0.00 0.00 2 0.00 0.00
std::_Vector_base<int,std::allocator<int> >::_M_deallocate(int*,unsigned long)
0.00 0.00 0.00 2 0.00 0.00
std::_Vector_base<int,std::allocator<int> >::_Vector_base(std::allocator<int> const&)
0.00 0.00 0.00 2 0.00 0.00 std::_Vector_base<int, std::allocator<int> >::~_Vector_base()
0.00 0.00 0.00 2 0.00 0.00 int*
std:: uninitialized_copy<true>:: uninit_copy<int*,int*>(int*, int*, int*)
0.00 0.00 0.00 2 0.00 0.00 void
std::vector<int,std::allocator<int> >::_M_range_initialize<int*>(int*, int*, std::forward_iterator_tag)
0.00 0.00 0.00 2 0.00 0.00 void
std::vector<int,std::allocator<int> >::_M_initialize_dispatch<int*>(int*, int*, std:: false_type)
0.00 0.00 0.00 2 0.00 0.00
std::vector<int,std::allocator<int> >::vector<int*>(int*,int*,std::allocator<int> const&)
0.00 0.00 0.00 2 0.00 0.00 std::vector<int, std::allocator<int> >::~vector()
0.00
std::iter
0.00
ator_tra
0.00 2
its<int*>::diff
0.00 0.00
erence_typestd:: distance<int*>(int*, int*, std::random_access_iterator_tag)
0.00
0.00
0.00
2
0.00
0.00
int* std:: copy_move_a<false, int*, int*>(int*, int*, int*)
0.00 0.00 0.00 2 0.00 0.00 int* std:: copy_move_a2<false, int*, int*>(int*, int*, int*)
0.00 0.00 0.00 2 0.00 0.00 int* std::uninitialized_copy<int*, int*>(int*, int*, int*)
0.00 0.00 0.00 2 0.00 0.00 std::iterator_traits<int*>::iterator_category
std:: iterator_category<int*>(int* const&)
0.00 0.00 0.00 2 0.00 0.00 int* std:: uninitialized_copy_a<int*, int*, int>(int*, int*, int*,
std::allocator<int>&)
0.00 0.00 0.00 2 0.00 0.00 int* std::copy<int*, int*>(int*, int*, int*)
0.00 0.00 0.00 2 0.00 0.00 void std::_Destroy<int*>(int*, int*)
0.00 0.00 0.00 2 0.00 0.00 void std::_Destroy<int*, int>(int*, int*, std::allocator<int>&)
0.00 0.00 0.00 2 0.00 0.00 std::iterator_traits<int*>::difference_type
std::distance<int*>(int*, int*)
0.00 0.00 0.00 1 0.00 0.00 _GLOBAL sub_I Z9partitionRSt6vectorIiSaIiEEiii
0.00 0.00 0.00 1 0.00 0.00 testPartition()
0.00 0.00 0.00 1 0.00 0.00 static_initialization_and_destruction_0(int, int)
0.00 0.00 0.00 1 0.00 0.00 qsort(std::vector<int, std::allocator<int> >&, int, int)
0.00 0.00 0.00 1 0.00 0.00 testSort()
% the percentage of the total running time of the
time program used by this function.
cumulative a running sum of the number of seconds accounted
seconds for by this function and those listed above it.
self the number of seconds accounted for by this
seconds function alone. This is the major sort for this
listing.
calls the number of times this function was invoked, if
this function is profiled, else blank.
self the average number of milliseconds spent in this
ms/call function per call, if this function is profiled,
else blank.
total the average number of milliseconds spent in this
ms/call function and its descendents per call, if this
function is profiled, else blank.
name the name of the function. This is the minor sort
for this listing. The index shows the location of
the function in the gprof listing. If the index is
in parenthesis it shows where it would appear in
the gprof listing if it were to be printed.
Copyright (C) 2012 Free Software Foundation, Inc.
Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved.
aman@aman-Inspiron-5520:~/Desktop/410454 Computer Laboratory-IV$
/*********************************************************************
ASSIGNMENT NO : B-6
TITLE : 6. Implement OBST Tree search using HPC task sub-division.
Merge the results to get final result. NAME : ROLL NO :
CLASS : BE COMPUTER
BATCH : B-3
********************************************************************/
obst1.c
#include <stdio.h>
#include<stdlib.h>
#define NMAX 20
typedef struct OBST
{
int KEY;
struct OBST *left, *right;
}OBST;
int C[NMAX][NMAX]; //cost matrix
int W[NMAX][NMAX]; //weight matrix
int R[NMAX][NMAX]; //root matrix
int q[NMAX]; //unsuccesful searches
int p[NMAX]; //frequencies
int NUMBER_OF_KEYS; //number of keys in the tree
int KEYS[NMAX];
OBST *ROOT;
void COMPUTE_W_C_R()
{
int x, min;
int i, j, k, h, m;
//Construct weight matrix W
for(i = 0; i <= NUMBER_OF_KEYS; i++)
{
W[i][i] = q[i];
for(j = i + 1; j <= NUMBER_OF_KEYS; j++)
W[i][j] = W[i][j-1] + p[j] + q[j];
}
//Construct cost matrix C and root matrix R
for(i = 0; i <= NUMBER_OF_KEYS; i++)
C[i][i] = W[i][i];
for(i = 0; i <= NUMBER_OF_KEYS - 1; i++)
{
j = i + 1;
C[i][j] = C[i][i] + C[j][j] + W[i][j];
R[i][j] = j;
}
for(h = 2; h <= NUMBER_OF_KEYS; h++)
for(i = 0; i <= NUMBER_OF_KEYS - h; i++)
{
j = i + h;
m = R[i][j-1];
min = C[i][m-1] + C[m][j];
for(k = m+1; k <= R[i+1][j]; k++)
{
x = C[i][k-1] + C[k][j];
if(x < min)
{
m = k;
min = x;
}
}
C[i][j] = W[i][j] + min;
R[i][j] = m;
}
//Display eight matrix W:\n");
printf("\nThe weight matrix W:\n");
for(i =0; i <= NUMBER_OF_KEYS; i++)
{
for(j=i; j <= NUMBER_OF_KEYS; j++)
printf("%d ", W[i][j]);
printf("\n");
}
//Display Cost matrix C
printf("\nThe cost matrix C:\n");
for(i = 0; i <= NUMBER_OF_KEYS; i++)
{
for(j = i; j <= NUMBER_OF_KEYS; j++)
printf("%d ", C[i][j]);
printf("\n");
}
//Display root matrix R
printf("\nThe root matrix R:\n");
for(i = 0; i <= NUMBER_OF_KEYS; i++)
{
for(j = i; j <= NUMBER_OF_KEYS; j++)
printf("%d ", R[i][j]);
printf("\n");
}
}
//Construct the optimal binary search tree
OBST *CONSTRUCT_OBST(int i, int j)
{
OBST *p;
if(i == j)
p = NULL;
else
{
//head = (NODE *)malloc(sizeof(NODE));
p=(OBST *)malloc(sizeof(OBST));
//p = new OBST;
p->KEY = KEYS[R[i][j]];
p->left = CONSTRUCT_OBST(i, R[i][j] - 1); //left subtree
p->right = CONSTRUCT_OBST(R[i][j], j); //right subtree
}
return p;
}
//Display the optimal binary search tree
void DISPLAY(OBST *ROOT, int nivel)
{
int i;
if(ROOT != 0)
{
DISPLAY(ROOT->right, nivel+1);
for(i = 0; i <= nivel; i++)
printf(" ");
printf("%d\n", ROOT->KEY);
DISPLAY(ROOT->left, nivel + 1);
}
}
void OPTIMAL_BINARY_SEARCH_TREE()
{
float average_cost_per_weight;
COMPUTE_W_C_R();
printf("C[0] = %d W[0] = %d\n", C[0][NUMBER_OF_KEYS],
W[0][NUMBER_OF_KEYS]);
average_cost_per_weight
=C[0][NUMBER_OF_KEYS]/(float)W[0][NUMBER_OF_KEYS];
printf("The cost per weight ratio is: %f\n",
average_cost_per_weight);
ROOT = CONSTRUCT_OBST(0, NUMBER_OF_KEYS);
}
int main()
{
int i, k;
printf("Input number of keys: ");
scanf("%d", &NUMBER_OF_KEYS);
for(i = 1; i <= NUMBER_OF_KEYS; i++)
{
printf("key[%d]= ",i);
scanf("%d", &KEYS[i]);
printf(" frequency = ");
scanf("%d",&p[i]);
}
for(i = 0; i <= NUMBER_OF_KEYS; i++)
{
printf("q[%d] = ", i);
scanf("%d",&q[i]);
}
while(1)
{
printf("1.Construct tree\n2.Display tree\n3.Exit\n");
scanf("%d", &k);
switch(k)
{
case 1:
OPTIMAL_BINARY_SEARCH_TREE();
break;
case 2:
DISPLAY(ROOT, 0);
break;
case 3:
exit(0);
break;
}
}
system("PAUSE");
}
/*
**********************************Output*****************************
aman@aman-Inspiron-5520:~$ sudo su
[sudo] password for aman:
root@aman-Inspiron-5520:/home/aman# ssh [email protected]
Debian GNU/Linux 7
BeagleBoard.org Debian Image 2015-03-01
Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian
default username:password is [debian:temppwd]
Last login: Sun Mar 1 20:51:37 2017 from aman@aman-Inspiron-5520:~$
root@beaglebone:~# cd ..
root@beaglebone:/# gcc obst1.c
root@beaglebone:/# ./a.out
Input number of keys: 6
key[1]= 1
frequency = 10
key[2]= 2
frequency = 3
key[3]= 3
frequency = 9
key[4]= 4
frequency = 2
key[5]= 5
frequency = 0
key[6]= 6
frequency = 10
q[0] = 5
q[1] = 6
q[2] = 4
q[3] = 4
q[4] = 3
q[5] = 8
q[6] = 0
1. Construct tree
2.Display tree
3.Exit
1
The weight matrix W:
5 21 28 41 46 54 64
6 13 26 31 39 49
4 17 22 30 40
4 9 17 27
3 11 21
8 18
0
The cost matrix C:
5 32 56 98 118 151 188
6 23 53 70 103 140
4 25 42 75 108
4 16 41 68
3 22 43
8 26
0
The root matrix R:
0 1 1 2 3 3 3
0 2 3 3 3 3
0 3 3 3 4
0 4 5 6
0 5 6
0 6
0
C[0] = 188 W[0] = 64
The cost per weight ratio is: 2.937500
1.Construct tree
2. Display tree
3.Exit
2
6
5
4
3
2
1
1.Construct tree
2.Display tree
3.Exit
3
root@beaglebone:/#
Broadcast message from root@beaglebone (Sun Mar 1 20:53:24 2017):
Power button pressed
The system is going down for system halt NOW!
Connection to 192.168.7.2 closed by remote host.
Connection to 192.168.7.2 closed.
aman@aman-Inspiron-5520:~$
*/
/*********************************************************************
ASSIGNMENT NO : B-7
TITLE : 7. Perform concurrent ODD-Even Merge sort using HPC
infrastructure (preferably BBB) using Python/Scala/ Java/ C++.
NAME : ROLL NO :
CLASS : BE COMPUTER BATCH : B-3
********************************************************************/
odd_even.c
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
int merge(double *ina, int lena, double *inb, int lenb, double *out) {
int i,j;
int outcount=0;
for (i=0,j=0; i<lena; i++) {
while ((inb[j] < ina[i]) && j < lenb) {
out[outcount++] = inb[j++];
}
out[outcount++] = ina[i];
}
while (j<lenb)
out[outcount++] = inb[j++];
return 0;
}
int domerge_sort(double *a, int start, int end, double *b) {
if ((end - start) <= 1) return 0;
int mid = (end+start)/2;
domerge_sort(a, start, mid, b);
domerge_sort(a, mid, end, b);
merge(&(a[start]), mid-start, &(a[mid]), end-mid, &(b[start]));
int i;
for (i=start; i<end; i++)
a[i] = b[i];
return 0;
}
int merge_sort(int n, double *a) {
double b[n];
domerge_sort(a, 0, n, b);
return 0;
}
void printstat(int rank, int iter, char *txt, double *la, int n) {
printf("[%d] %s iter %d: <", rank, txt, iter);
int i,j;
for (j=0; j<n-1; j++)
printf("%6.3lf,",la[j]);
printf("%6.3lf>\n", la[n-1]);
}
void MPI_Pairwise_Exchange(int localn, double *locala, int sendrank, int recvrank,
MPI_Comm comm) {
/*
* the sending rank just sends the data and waits for the results;
* the receiving rank receives it, sorts the combined data, and returns
* the correct half of the data.
*/
int rank;
double remote[localn];
double all[2*localn];
const int mergetag = 1;
const int sortedtag = 2;
MPI_Comm_rank(comm, &rank);
if (rank == sendrank) {
MPI_Send(locala, localn, MPI_DOUBLE, recvrank, mergetag,
MPI_COMM_WORLD);
MPI_Recv(locala, localn, MPI_DOUBLE, recvrank, sortedtag,
MPI_COMM_WORLD, MPI_STATUS_IGNORE);
} else {
MPI_Recv(remote, localn, MPI_DOUBLE, sendrank, mergetag,
MPI_COMM_WORLD, MPI_STATUS_IGNORE);
merge(locala, localn, remote, localn, all);
int theirstart = 0, mystart = localn;
if (sendrank > rank) {
theirstart = localn;
mystart = 0;
}
MPI_Send(&(all[theirstart]), localn, MPI_DOUBLE, sendrank, sortedtag,
MPI_COMM_WORLD);
int i;
for (i=mystart; i<mystart+localn; i++)
locala[i-mystart] = all[i];
}
}
int MPI_OddEven_Sort(int n, double *a, int root, MPI_Comm comm)
{
int rank, size, i;
double *local_a;
// get rank and size of comm
MPI_Comm_rank(comm, &rank); //&rank = address of rank
MPI_Comm_size(comm, &size);
local_a = (double *) calloc(n / size, sizeof(double));
// scatter the array a to local_a
MPI_Scatter(a, n / size, MPI_DOUBLE, local_a, n / size, MPI_DOUBLE,
root, comm);
// sort local_a
merge_sort(n / size, local_a);
//odd-even part
for (i = 1; i <= size; i++) {
printstat(rank, i, "before", local_a, n/size);
if ((i + rank) % 2 == 0) { // means i and rank have same nature
if (rank < size - 1) {
MPI_Pairwise_Exchange(n / size, local_a, rank, rank + 1, comm);
}
} else if (rank > 0) {
MPI_Pairwise_Exchange(n / size, local_a, rank - 1, rank, comm);
}
}
printstat(rank, i-1, "after", local_a, n/size);
// gather local_a to a
MPI_Gather(local_a, n / size, MPI_DOUBLE, a, n / size, MPI_DOUBLE,
root, comm);
if (rank == root)
printstat(rank, i, " all done ", a, n);
return MPI_SUCCESS;
}
int main(int argc, char **argv) {
MPI_Init(&argc, &argv);
int n = argc-1;
double a[n];
int i;
for (i=0; i<n; i++)
a[i] = atof(argv[i+1]);
MPI_OddEven_Sort(n, a, 0, MPI_COMM_WORLD);
MPI_Finalize();
return 0;
}
/*
**********************************Output*****************************
aman@aman-Inspiron-5520:~$ cd openmpi/ openmpi-1.10.2/ examples/
aman@aman-Inspiron-5520:~/openmpi/openmpi-1.10.2/examples$ mpicc
odd_even.c -o odd_even
aman@aman-Inspiron-5520:~/openmpi/openmpi-1.10.2/examples$ mpirun -np
2 ./odd_even 45 96 41 3 8 77 56 65 20 14 1
[1] before iter 1: <14.000,20.000,56.000,65.000,77.000>
[1] before iter 2: <14.000,20.000,56.000,65.000,77.000>
[1] after iter 2: <45.000,56.000,65.000,77.000,96.000>
[0] before iter 1: < 3.000, 8.000,41.000,45.000,96.000>
[0] before iter 2: < 3.000, 8.000,41.000,45.000,96.000>
[0] after iter 2: < 3.000, 8.000,14.000,20.000,41.000>
[0] all done iter 3: < 3.000,
8.000,14.000,20.000,41.000,45.000,56.000,65.000,77.000,96.000, 1.000>
aman@aman-Inspiron-5520:~/openmpi/openmpi-1.10.2/examples$
*/
/*********************************************************************
ASSIGNMENT NO : Group B-Elective-IV A1
TITLE : Elective-IV A1 A Mall has number of items for sale. Build a
required Database to develop BAI tool for considering one
aspect of growth to the business Such as organization of
products based on demand and patterns use R Programming or
other equivalent latest tools used in Industry or Use Hadoop,
HDFS, HIVE, PIG,mongoBD Connectors for Hadoop and/OR
other latest technology tools in the Hadoop Ecosystem for
unstructured data analytics to effectively use advanced SQL
functions and Greenplum extensions for in-database analytics.
Use MADlib bigdata tools to solve analytics problems in-
database Used for this assignment
NAME : ROLL NO :
CLASS : BE COMPUTER
BATCH : B-3
********************************************************************/
/*********************************************************************
ASSIGNMENT NO : B-3
TITLE : 3. Develop a stack sampling using threads using VTune
Amplifier.
NAME : ROLL NO :
CLASS : BE COMPUTER
BATCH : B-3
********************************************************************/
qsort.cpp #include <iostream> #include <vector>
using namespace std;
/** * Partition the elements of 1st (A), such that first have elements
smaller than
* "who", followed by elements larger than "who". Return the last
position of an
* element smaller or equal to "who".
*/
int partition(vector<int>& A, int left, int right, int who) {
for (int i=left; i<right; ++i) {
if (A[i] <= who) {
swap(A[i], A[left]);
left ++;
} }
return left - 1;
}
/**
* Quick sort vector A, between index "left" and index "right".
*/
void qsort(vector<int>& A, int left, int right) {
if (left >= right) return;
int middle = left + (right - left) / 2; //find out middle element
swap(A[middle], A[left]);
int midpoint = partition(A, left + 1, right, A[left]);
swap(A[left], A[midpoint]);
qsort(A, left, midpoint);
qsort(A, midpoint + 1, right);
}
void printVector(vector<int>& A) {
for (int i=0; i<A.size(); ++i) {
cout << A[i] << " ";
}
cout << endl;
}
void testPartition() {
int elements[] = {1, 3, 1, 1, 3};
vector<int> A(elements, elements + 5);
int n = partition(A, 0, 5, 1);
cout << n << endl;
printVector(A);
}
void testSort() {
int elements[] = {1, 12,5, 2,7, 6, 20, 25};
vector<int> A(elements, elements + 8);
qsort(A, 0, A.size());
printVector(A);
}
int main ()
{
testPartition();
cout << "---------------" << endl; testSort();
return 0;
}