0% found this document useful (0 votes)
123 views8 pages

A Comparative Study Between The Greedy and Dynamic Technique For Better Optimization Performance

Greedy algorithms can be classified as blind. In a simple way, it always looks to the future and does not look back on the past
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views8 pages

A Comparative Study Between The Greedy and Dynamic Technique For Better Optimization Performance

Greedy algorithms can be classified as blind. In a simple way, it always looks to the future and does not look back on the past
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Volume 6, Issue 10, October – 2021 International Journal of Innovative Science and Research Technology

ISSN No:-2456-2165

A Comparative Study between the Greedy and


Dynamic Technique for Better Optimization
Performance
Mirza Samiulla Beg, Ph.D. Scholar, Department of Computer Science & IT, AKS University,Satna
Akhilesh A. Waoo, Head, Department of Computer Science & IT, AKS University, Satna

Abstract:- Greedy algorithms can be classified as blind. Advantages and Disadvantages - Greedy Algorithm
In a simple way, it always looks to the future and does 1. It's easy to come back with a greedy algorithm (or even
not look back on the past. All the greed you are trying to more greedy algorithms) for drag.
achieve is trying to accumulate the best value in the 2. Analyzing the duration of the operation of greedy
solutions at hand, even though some of the solutions may algorithms will generally be much easier than other
be very useful in the future. The Dynamic (DP) system is methods (like Divorce and Win). Separating and winning
different from greed in the way in which an improved the process, it is not clear whether the process is fast or
solution is selected. As mentioned earlier, greedy people slow. This is common because at each repetition level
are constantly on the lookout for profits without regard the size is smaller and therefore the number of minor
for the future or the past. DP produces all possible problems increases.
solutions from handmade solutions, and then re- 3. The hard part is that in the greedy algorithms you must
evaluates and re-runs all of them to choose the best find it very difficult to know the issues of righteousness.
solution. In this paper, I want to tell you that a strong Even with the right algorithm, it is difficult to prove why
process gives better results than the method of greed. It it is correct. Proving that the selfish algorithm is right is
can therefore be said that if we apply the dynamic more art than science. Includes tons of art.
techniques in the Artificial Bee Colony Algorithm, then
it will give us better results. In this paper, I have shown III. ARTIFICIAL BEE COLONY (ABC)
that motivation strategies are better. ALGORITHM

Keywords:- WSN (Wireless Sensor Network), ABC The Artificial Bee Colony (ABC) algorithm is an
(Artificial Bee Colony) Algorithm, DP (Dynamic optimization algorithm that mimics the performance of a bee
Technique), BS (Base Station), IoT (Internet of Things). colony and was first proposed by Karaboga in 2005 to use
the actual parameter.In this mathematical example, our bee
I. INTRODUCTION colony is made up of three types of bees: Worker Bees,
which will work in collecting food in the hive at a specific
The greedy algorithm can be a group of algorithms food source. Bees are called Onlooker Bees, which will
with one common feature, making it the easiest choice in guard workers to ensure that a particular food source is no
each area for each step without looking at the programs. longer suitable, as well as Scout bees, which will seek out
Therefore, the essence of the greed algorithm can be a task new sources of food.
of choice: given the group of options, select the best option
currently. Due to the myopic nature of the greedy algorithm, In the ABC algorithm, the food source is defined as a
(as expected) is incorrect in several problems. However, position in the search space (solution for the problem of
certain problems can be easily solved using the greedy efficiency), and initially, the number of feed sources is equal
algorithm, which can be shown to be correct. to the number of bees in the hive. The quality of the food
source is determined by the amount of objective activity in
II. GREEDY ALGORITHM that position (the amount of consistency).The emerging
behavior of bees can be summed up in a few steps:
The greedy algorithm, because the name suggests, • Bees start randomly exploring the environment in search
always makes choices that seem the easiest now. this of good food sources (value).
suggests that it makes a good choice in the area within the • After finding a source of food, the bee becomes a worker
hope that this choice will create the right global bee and begins to extract food from the discovered
solution.Assume that you have a purposeful task that needs source.
to be prepared (or enlarged or reduced) somewhere. The • The worker bee returns to the hive with nectar and
greedy algorithm makes greedy choices at every step to releases the nectar. After extracting the nectar, he can
ensure that the targeted work is done. The greedy algorithm return directly to his found domain directly or share
has only one gun to calculate the right solution so it doesn’t information about his source location by performing a
go back and change the selection. Many greedy algorithms dance on the dance floor.
are incorrect.

IJISRT21OCT450 www.ijisrt.com 846


Volume 6, Issue 10, October – 2021 International Journal of Innovative Science and Research Technology
ISSN No:-2456-2165
• When the food supply is exhausted, the worker bee remote sensor network that the bunch head hubs can speak
becomes a spout and begins randomly in search of a new with a base station (BS) hub straightforwardly, which causes
source of food. that the group head hubs burn-through an excessive amount
• Observing bees waiting in the hive observe bees working of energy and become the bottleneck of organization
in the collection of their food source and select the execution. Accordingly, a WSN geography calculation
source among the most profitable sources. dependent on avaricious most limited ways is proposed in
• The choice of food source is equal to the quality of the this paper. Right off the bat, choosing the spine hubs of the
source (number of solids). organization and building the spine organization to send
messages, and permitting the spine hubs and group heads to
exist independently. Also, the spine hubs construct a solitary
To do these things we can use the method of greed and source briefest way directing table dependent on the
use Dynamic. So here is the definition of both algorithms. covetous calculation and select the most appropriate most
And make it clear that Dynamic is better than stubborn. limited way to send information as per the utilization of the
spine hubs. Thirdly, choosing the group heads is dependent
IV. DYNAMIC TECHNIQUE on the LEACH convention, in which the bunch heads are
answerable for gathering and packing the information,
Dynamic planning can be a way to divide issues into choosing the closest spine hub to send the information. It is
smaller issues and save results for future purposes so that we shown by information estimation and investigation that the
don't have to re-calculate the results. The underlying proposed geography conspires in this paper have a more
problems are designed to add a common solution is steady transmission network structure, less weight, and less
understood as a good site for reconstruction. Excessive use remaking recurrence, and the group heads are just
of a powerful system to open up performance problems. answerable for moving the prepared information to the spine
Here, performance issues mean that if we are trying to find a organization. Also, the bunch head utilization and the
minimum or a great drag solution. A powerful system general organization utilization are altogether worked on
ensures finding the right solution to drag when the answer is contrasted and LEACH.
available. The definition of a powerful system states that it
is a way to solve a posh problem by first logging into a set Seyed Reza Nabavi et al [3] suggested due to the
of simple problems, solving each problem at once, and then widespread use of communication networks and the ease of
keeping their solutions to avoid duplicate calculations. transmitting and collecting information about these
networks, WSN wireless networks are becoming
V. REVIEW OF LITERATURE increasingly popular. The usability of any area without the
need for environmental monitoring and engineering of these
K. Lin et al [1] presented a remote sensor organization networks has led to its increasing use in various fields.
(WSN) ordinarily works in a problematic remote climate Moving data from a sensor node to a sink, so that the power
with energy limitations. Numerous specialists are of the node is consumed uniformly and network life can be
fundamentally intrigued by the energy mindfulness and reduced, is one of the most important challenges for wireless
correspondence dependability of WSNs to amplify network sensor networks. Most wireless networks do not have the
lifetime. Be that as it may, managing the clashing issues of infrastructure, and embedded sensor nodes have limited
further developing energy proficiency and adaptation to power. Therefore, the initial term of the wireless node power
internal failure all the while is a difficult undertaking. Most based on network messaging may disrupt the entire network
past investigations have shown that the two issues can be process. In this paper, the object is designed to determine
drawn nearer by utilizing either information connection or the correct path to WSN based on the multi-objective greed
organization layer conventions. They present a cross-layer method of the nearest route. The proposed model is
convention, which incorporates a multipath steering presented in this way to transfer sensor network information
convention and an information interleaving strategy to the base station of the desired applications. In this way,
dependent on the Reed-Solomon code. They define the issue the sensor nodes are identified as adjacent nodes based on
of choosing sensor transmission ways as a backpack issue their distance. The power of all places is initially almost
and tackle it by an avaricious calculation. Our multipath equal, diminished by the transfer of information between
directing convention then, at that point, empowers every places. This way, when a node hears a message, it looks for
sensor to choose numerous transmission ways utilizing the several data transfer objects in its nearby nodes and selects a
proposed streamlining calculation. Based on numerous node with several larger objects such as the next hop.
transmission ways, the method of information interleaving is Imitation results show that power consumption on network
utilized by utilizing the Reed-Solomon code to give solid grids is almost equally presented, and network life is
information transmission. Reenactment results show that our reduced by a small slope that provides optimal power
plan beats the current multipath directing conventions consumption to networks. Also, the packet transfer delay in
concerning the organization's lifetime since it adjusts energy the network is up to 450 milliseconds of data transmission
utilization and advances correspondence unwavering between 15 nodes and 650 connections. Besides, network
quality. penetration increases by about 97%. It also shows better
performance compared to other previous methods in terms
X. Wang et al [2] proposed it is a generally expected of testing.
plan in the majority of the current geography plans of

IJISRT21OCT450 www.ijisrt.com 847


Volume 6, Issue 10, October – 2021 International Journal of Innovative Science and Research Technology
ISSN No:-2456-2165
Ahmed RedhaMahlous et al [4] presented they have the following dominators. They likewise propose an
seen an expanding interest in creating and planning Wireless approach to lessen the CDS size by minimizing a portion of
Sensor Networks (WSNs). WSNs comprise an enormous the current dominators after the development of CDS. The
number of hubs, with remote correspondences and reproduction result shows that our CDS development
calculation capacities that can be utilized in an assortment of conspire beats every one of the current CDS development
spaces. It has been utilized in regions that have direct calculations as far as CDS size for arbitrarily dispersed
contact with observing and assembling information, to name hubs. Our calculation holds the presentation proportion of
not many, wellbeing checking, military observation, land (4.8 + ln5)opt + 1.2 and time intricacy of O(D), where pick
checking (Earthquakes, Volcanoes, Tsunami), agribusiness being the size of the ideal CDS and D is the measurement of
control, and some more. Be that as it may, the plan and the organization.
execution of WSNs face many difficulties, because of the
force limit of sensor hubs, arrangement, and confinement, Q. Q. Shi et al [7] suggested geographic directing
information directing and information collection, conventions for remote sensor organizations (WSNs) have
information security, restricted data transmission, gotten more consideration lately and ravenous sending
stockpiling limit, and organization of the board. It is realized calculation is the primary part of geographic steering. They
that Operation Research (OR) has been broadly utilized in research the sending models in ravenous sending
various regions to take care of advancement issues, for calculations and present an eager steering calculation
example, further developing organization execution and utilizing another basis joining the qualities of both distance-
amplifying the lifetime of framework. They present the based rule and course-based rule. Reenactment is given to
latest OR-based procedures applied to take care of various contrast the exhibition of our calculation and those of the
WSNs issues: the hub booking issue, energy the executive's calculation with the distance-based model and the
issues, hubs apportioning issues, and other WSNs related calculation with the heading-based standard. The outcomes
complex issues. Distinctive Operational Research methods show that our proposed calculation is a favored choice as far
are introduced and examined in subtleties here, including as the compromise between change postponement and
chart hypothesis-based procedures, direct programming, and energy utilization in the steering.
blended whole number programming-related methodologies.
Y. Xin et al [8] presented in the utilization of remote
Sadek et al [5] proposed one of the focal sensor organizations (WSN), the equilibrium of energy
correspondence frameworks of the Internet of Things (IoT) utilization assumes a significant part in broadening the
is the IEEE 802.15.4 norm, which characterizes Low Rate existing pattern of WSN. Focus on the energy utilization of
Wireless Personal Area Networks (LR-WPAN). To share remote sensors organization, a powerful group put together
the medium genuinely in a non-signal empowered mode, the directing convention-based for the avaricious calculation
standard uses Carrier Sense Multiple Access with Collision (GDP). In the convention, hubs run for the group head as per
Avoidance (CSMA/CA). The idea of associated objects the energy and area. The chosen group head has an ideal
concerning different asset limitations makes them powerless worth of energy and area. At the point when the group is
against digital assaults. Quite possibly the most forceful Do framed, the sink hub starts the solicitation of directing
assaults is the voracious conduct assault which intends to foundation; the bunch heads pick the hubs that send the
deny genuine hubs to admittance to the correspondence bundle as the upper hubs as per energy and bounces build-
medium. The covetous or egotistical hub might disregard the up to the sink hub. After a time of the organization working,
appropriate utilization of the CSMA/CA convention, by then, at that point, pick hubs as indicated by the energy
altering its boundaries, to take however much data worth and distance as the bunch head indeed to stay away
transmission as could be expected on the organization, and from network disappointment as a result of one hub
afterward consume admittance to the medium by denying disappointment. The convention adjusts the energy
real hubs of correspondence. In light of the examination of utilization of the organization's impact and expands the
the contrast between boundaries of ravenous and authentic existing pattern of the whole organization.
hubs, they propose a technique dependent on the limit
system to distinguish avaricious hubs. The recreation results S. Bousnina et al [9] proposed Virtual Sensor
show that the proposed component gives a recognition Networks (VSNs) imagine the making of universally useful
proficiency of 99.5%. remote sensor networks which can be effortlessly adjusted
and arranged to help multifold applications with
J. P. Mohanty et al [6] presented in the specially heterogeneous prerequisites, interestingly, with the
appointed remote organization, there is no predefined traditional methodology of remote sensor networks upward
framework. In this way, hubs speak with one another enhanced on one explicit undertaking/administration. The
through peer interchanges. For powerful correspondence, an actual heart of VSNs' vision is the capacity to powerfully
associated overwhelming set (CDS) can be utilized as a distribute shared actual assets (handling power, data
virtual spine for the organization. Notwithstanding, building transmission, stockpiling) to various approaching
a base-associated ruling set is an NP-Complete issue. In the applications. In this unique circumstance, they tackle the
writing, numerous estimation calculations have been issue of ideally dispensing shared assets in VSNs by
accounted for. In this paper, they propose a conveyed three- proposing a proficient avaricious heuristic that intends to
stage insatiable guess calculation. In our calculation, the expand the complete income out of the sending of different
hubs just store one-jump neighborhood data to track down simultaneous applications while thinking about the intrinsic

IJISRT21OCT450 www.ijisrt.com 848


Volume 6, Issue 10, October – 2021 International Journal of Innovative Science and Research Technology
ISSN No:-2456-2165
limits of the common actual assets. The proposed heuristic Consequently, if a ravenous hub acts correspondingly as in
is tried on reasonable organization occasions with the WLAN case, attempting to starve its neighbors, then, at
remarkable exhibitions as far as execution time while that point, its next bounce sending hub will likewise be
keeping the hole as for the ideal arrangement restricted forestalled to advance its traffic, which prompts a start to
(beneath 5% in the tried conditions). finish throughput breakdown. In this paper, they show that
to have a more helpful insatiable conduct in remote specially
L. Ban-teng et al [10] suggested Remote Sensor appointed organizations, a hub should embrace an
Networks(WSN) are a problem area of the examination of unexpected methodology in comparison to WLAN to
remote organizations right now, the key to accomplishing a accomplish its very own superior exhibition streams. They
proficient transmission business is to control hub energy and present a technique to dispatch a particularly insatiable
further develop the organization lifetime in remote sensor assault in a proactive directing based remote specially
organizations. The paper first uses Boolean detecting model appointed organization. Through the broad reproductions,
dependent on Poisson direct interaction toward recognize the acquired outcomes show that by applying the proposed
the capacity of the pace of inclusion and the hub thickness calculation, a ravenous hub can acquire more data
in-unit region and afterward computes the all outnumber of transmission than its neighbors and keep the start to finish
hubs in the locale, next utilize the avaricious technique of throughput of its streams profoundly sensible.
the Prim calculation to discover a traversing tree with the
most extreme weight, and builds a surmised answer for the Tzu-Chiang et al [13] suggested with the benefit of
base associated ruling set. To control the upheavals of the remote organization innovation, there are assortments of
hubs, make the hubs in the crossing tree work, and different portable applications which make the issue of remote sensor
hubs are in a rest state. Finally, further examination of the networks a well-known exploration region lately. As the
connection between the number of hubs in associated remote sensor network hubs move self-assertively with the
overwhelming and the inclusion sweep. geography quick-change highlight, portable hubs are
frequently defied with the void issue which will start parcel
H. A. Hamzah et al [11] presented accuracy cultivating losing, retransmitting, rerouting, extra transmission cost, and
as a cultivating the board idea dependent on noticing, force utilization. When sending parcels, they would not
estimating, and reacting to the shifting harvests' necessities. foresee void issues happening ahead of time. Consequently,
For this examination, Wireless Sensor Network (WSN) is how to work on geographic steering with void evasion in
proposed to be carried out inaccuracy cultivating to go about remote organizations turns into a significant issue. In this
as a choice emotionally supportive network for the ranchers. paper, they proposed a covetous topographical void steering
Notwithstanding, WSN customary framework specifically calculation to take care of the void issue for remote sensor
the Direct Transmission (DT) convention experiences high organizations. They utilize the data of the source hub and
energy utilization, decreasing the observing capacity of the void region to attract two digressions to shape a fan scope of
ranchers because of the quick energy-exhausting sensor the current void which can declare void keeping away from
hubs. Recognizing this issue, analysts had created numerous the message. Then, at that point, they use source and
conventions, for example, Quality of Service (QoS), Low objective hubs to define a boundary with a point of the fan
Energy Adaptive Clustering Hierarchy (LEACH), Location- reach to choose the following sending neighbor hub for
based, and Power-Efficient Gathering in Sensor Information directing. In a unique remote sensor network climate, the
System (PEGASIS). For this exploration, PEGASIS is proposed ravenous void staying away from calculation can
chosen for its high energy proficiency and similarity with be additional efficient and more proficient to advance
the proposed framework. As distances influence bundles and work on the current geological void issue of
significantly energy utilization, Particle Swarm remote sensor organizations.
Optimization (PSO) is created to supplant ravenous
calculation in PEGASIS to diminish the distances of VI. IMPLEMENTATION OF GREEDY
information transmission. From the tests, PSO can diminish ALGORITHM
the absolute chain distance (TCD) by dependent upon 7.69%
in contrast with the insatiable calculation. Greedy algorithms can be classified as blind. In its
simplest way, it looks always for the future and doesn’t look
Djahel et al [12] proposed while the issue of ravenous back to the past. All that Greedy is trying to achieve is to try
conduct at the MAC layer has been broadly investigated to collect the best benefit from the solutions in hand,
with regards to the remote neighborhood, its review for regardless of whether some other solutions can be more
multi-bounce remote organizations is still just about a beneficial at another moment of time in the future.
neglected and unexplained issue. Without a doubt, in a
remote neighborhood, a passageway for the most part # Greedy Algorithm for a Optimisation Problem
advances bundles sent by remote hubs over the wired # Defined a class for item,with its name, value, and cost
connection. For this situation, a voracious hub can class Itm(object):
undoubtedly get more transmission capacity share and starve def __init__(self, name, val, cost):
any remaining related battling hubs by astutely controlling self.name = name
the MAC layer boundaries. In any case, in a remote self.val = val
specially appointed climate, all bundles are communicated self.cost = cost
in a multi-bounce style over remote connections. def getvalue(self):

IJISRT21OCT450 www.ijisrt.com 849


Volume 6, Issue 10, October – 2021 International Journal of Innovative Science and Research Technology
ISSN No:-2456-2165
return self.val return self.weight
def getcost(self): def getValue(self):
return self.cost return self.value
def __str__(self): def __str__(self):
return self.name return str(self.weight)+" , "+ str(self.value)

# Defining a function for building a List def getData(items):


# which generates list of items that are w = []
# available at supermart v = []
def buildlist(names, values, costs): for ob in items:
menu = [] w.append(ob.weight)
for i in range(len(names)): v.append(ob.value)
menu.append(Itm(names[i], values[i], costs[i])) return (w,v)
return menu
def buildItem(W,V,keyfunction,reverse):
# Implementation of greedy algorithmto choose one of the items = []
optimum choice for i in range(len(W)):
def greedy (items, maxcal, keyfunction): ob = Item(W[i],V[i])
itemscopy = sorted(items, key = keyfunction, reverse = items.append(ob)
True) return items
result = []
totalval = 0 def dynamic(maxWeight,items):
totalcal = 0 weight,value = Item.getData(items)
n = len(value)
for i in range(len(items)): S = [[0 for x in range(maxWeight+1)] for k in range(n+1)]
if (totalcal + itemscopy[i].getcost() <= maxcal): for x in range(1, maxWeight+1):
result.append(itemscopy[i]) for k in range(1, n+1):
totalval = totalval + itemscopy[i].getvalue() S[k][x] = S[k-1][x]
totalcal = totalcal + itemscopy[i].getcost() if weight[k-1] <= x andS[k-1][x-weight[k-1]]+value[k-
return (result, totalval,totalcal) 1]>S[k][x]:
S[k][x] = S[k-1][x-weight[k-1]] + value[k-1]
# Main Function# All values are random data = list()
names = ['Ball', 'Gloves', 'Notebook', 'Bagpack', 'Charger', for i in range(len(S)-1,-1,-1):
'Pillow', 'Cakes', 'Pencil'] arr = S[i]
values = [89,90,95,100,90,79,50,10] maxNum = max(arr)
costs = [123,154,25,145,365,150,95,195] #print("\n>>> M >> ",maxNum)
if maxNum not in S[i-1] and maxWeight> weight[i-1]:
Itemrs = buildlist(names, values, costs) data.append((weight[i-1],value[i-1]))
maxcost = 500 # maximum money he have to spend #print(data)
taken, totvalue,totalcal = greedy(Itemrs, maxcost, maxWeight-= weight[i-1]
Itm.getvalue) if maxWeight==0:
print('Total value taken : ', totvalue,totalcal) break
# Printing the list of item slected for optimum value return data
for i in range(len(taken)): maxWeight = 500
print(' ', taken[i]) w = [100,90,79,89,90,95,50,10]
Output: Total value taken : 374 , 447 v = [145,365,150,123,154,25,95,195]

Dynamic-Programming Algorithm itemList1 = buildItem(w,v,Item.getWeight,False)


Dynamic programming (DP) is different from greedy result = dynamic(maxWeight,itemList1)
in the way in which the optimized solution is selected. As print(result)
mentioned earlier, greediness always seeks the maximum wSum = 0
available profit without looking for the future or the past. vSum = 0
DP generates all feasible solutions from the solutions in for it in result:
hand, then iterates again through all of them to select the wSum += it[0]
best solution. vSum += it[1]
print("Total Weight : " , wSum," Price : ",vSum)
class Item: Output:[(145, 100), (25, 95), (154, 90), (123, 89)]
def __init__(self,weight,value): Total Weight: 447 Price: 374
self.weight = weight
self.value = value
def getWeight(self):

IJISRT21OCT450 www.ijisrt.com 850


Volume 6, Issue 10, October – 2021 International Journal of Innovative Science and Research Technology
ISSN No:-2456-2165
Test Cases for Dynamic vs Greedy #print(">>> ",wl)
key = None
Test 1 : maxcost = 500 # maximum spending weight = None
values = [89,90,95,100,90,79,50,10] for data in wl:
costs = [123,154,25,145,365,150,95,195] if key is None:
According Greedy:Weight:374 , Price : 447 key = data.get('key')
According Dynamic:Weight:447,Price: 374 weight = data.get('weight')
else:
In this test find the maximum weight and minimum if data.get('weight') > weight:
price. The greedy test gives the weight 374 and price 447 key = data.get('key')
which is not an accurate result. When implement with the weight = data.get('weight')
dynamic test then get the weight 447 and price is 374 which return {'key':key , 'weight' : weight}
is an accurate result. So the dynamic test gives the
maximum weight and minimum price. def findMin(wl):
#print(">>> ",wl)
Test 2:maxcost = 600 # maximum spending key = None
values = [89,90,95,100,90,79,50,10] weight = None
costs = [123,154,25,145,365,150,95,195] for data in wl:
According Greedy:Weight:453,Price: 597 if key is None:
According Dynamic:Weight:597,Price: 453 key = data.get('key')
weight = data.get('weight')
In this test find the maximum weight and minimum else:
price. The greedy test gives the weight 453 and price 597 if data.get('weight') < weight:
which is not an accurate result. When implement with the key = data.get('key')
dynamic test then get the weight 597 and price is 453 which weight = data.get('weight')
is an accurate result. So the dynamic test gives the return {'key':key , 'weight' : weight}
maximum weight and minimum price.
def greedy(source,destination,isMinimum=True):
Test 3:maxcost = 400 # maximum spending path = {'key': source.getName() , 'weight' : 0}
values = [10,20,15,12,14,10,12,16,14,18,12,12,10,12,23] nd = source
costs = [67,78,45,34,12,78,56,45,23,12,45,67,89,34,32] while True:
According Greedy:Weight:99,Price: 337 if nd.getConnectedNodes() is None and nd.getName() is
According Dynamic:Weight:143,Price: 371 not destination.getName():
raise Exception("Destination Node Not Found !")
In this test find the maximum weight and maximum elifnd.getConnectedNodes() is None and nd.getName() is
price. The greedy test gives the weight 99 and price 337 destination.getName():
which is not an accurate result. When implement with the return path
dynamic test then get the weight 143 and price is 371 which else:
is an accurate result. So the dynamic test gives the if len(nd.getConnectedNodes())==1:
maximum weight and minimum price. node = nd.getConnectedNodes()[0]

Minimum and Maximum Path Using Greedy and newkey = path.get('key') + node.get('node').getName()
Dynamic Technique newweight = path.get('weight') + node.get('weight')
Node.py path.update({'key':newkey,'weight':newweight})
class Node: nd = node.get('node')
def __init__(self,name): else:
self.name = name weightlst = []
self.next = None for nodelist in nd.getConnectedNodes():
def setConnectedNodes(self,lst): node = nodelist.get('node')
if type(lst) is list: weight = nodelist.get('weight')
self.next = lst weightlst.append({'key':node,'weight':weight})
else:
raise Exception("Node list is required !") if isMinimum:
def getName(self): final = findMin(weightlst)
return self.name else:
def getConnectedNodes(self): final = findMax(weightlst)
return self.next
newkey = path.get('key')+ final.get('key').getName()
Greedy.py newweight = path.get('weight')+ final.get('weight')
from node import Node path.update({'key':newkey,'weight':newweight})
def findMax(wl): nd = final.get('key')

IJISRT21OCT450 www.ijisrt.com 851


Volume 6, Issue 10, October – 2021 International Journal of Innovative Science and Research Technology
ISSN No:-2456-2165
Dynamic.py Find Minimum Path Using Greedy and Dynamic
from node import Node Technique
def findMax(wl):
#print(">>> ",wl)
key = None
weight = None
for data in wl:
if key is None:
key = data.get('key')
weight = data.get('weight')
else:
if data.get('weight') > weight:
key = data.get('key')
weight = data.get('weight')
return {'key':key , 'weight' : weight}
Greedy Result: {'weight': 34, 'key': 'ABEHK'}
def findMin(wl): Dynamic Result: {'key': 'ADGJK', 'weight': 19}
#print(">>> ",wl)
key = None In this graph find the minimum path using the greedy
weight = None and dynamic techniques. When finding the minimum path
for data in wl: using the greedy technique get that path ‘ABEHK’ and
if key is None: weight is 34. When finding the path using the dynamic
key = data.get('key') technique get that path ‘ADGJK’ and weight is 19. So here
weight = data.get('weight') the dynamic technique gives the minimum path which is 19.
else: So the dynamic technique is best as compared to the greedy
if data.get('weight') < weight: technique.
key = data.get('key')
weight = data.get('weight') Find the Maximum path using Greedy and Dynamic
return {'key':key , 'weight' : weight} Technique.

def dynamic(source,destination,isMinimum=True):
path = []
nd = source
while True:
if nd.getConnectedNodes() is None and nd.getName() is
not destination.getName():
raise Exception("Destination Node Not Found !")
elifnd.getConnectedNodes() is None and nd.getName() is
destination.getName():
return {'key':nd.getName(),'weight':0}
else:
weightlst = []
for nodelist in nd.getConnectedNodes(): Greedy Result:{'key': 'ADGJK', 'weight': 19}
node = nodelist.get('node') Dynamic Result: {'weight': 36, 'key': 'ACFIK'}
nm = dynamic(node,destination)
#print(nm) In this graph find the maximum path using the greedy
and dynamic techniques. When finding the maximum path
name = nd.getName() + nm.get('key') using the greedy technique get that path 'ADGJK' and
weight = nodelist.get('weight') + nm.get('weight') weight is 19. When finding the path using the dynamic
weightlst.append({'key':name,'weight':weight}) technique get that path ‘ACFIK’ and weight is 36. So here
if len(nd.getConnectedNodes())==1: the dynamic technique gives the maximum path which is 36.
final = weightlst[0] So the dynamic technique is best as compared to the greedy
else: technique.
if isMinimum:
final = findMin(weightlst) VII. CONCLUSION
else:
final = findMax(weightlst) In this paper, a comparative study of the Greedy and
#print(source.getName() , " final : " , final) Dynamic techniques has been done. This study is done by
return final taking a graph. On which who uses the short and long path
to go from the source to the destination. When we studied
then we came to know that Dynamic Technique is better

IJISRT21OCT450 www.ijisrt.com 852


Volume 6, Issue 10, October – 2021 International Journal of Innovative Science and Research Technology
ISSN No:-2456-2165
than Greedy Technique, because when we search short path [10]. L. Ban-teng, C. You-rong, Z. Kai and J. Hua, "The
then Greedy Technique using this 'ABEHK' path gives us 34 Research of Wireless Sensor Networks Optimization
as result, while Dynamic Technique Using this 'ADGJK' Algorithm Based on the Energy Control," 2010 Third
path gives us 19 as the result, which is the best result. International Symposium on Information Processing,
Similarly, when we search for longer paths, the Greedy 2010, pp. 420-422, doi: 10.1109/ISIP.2010.83.
technique gives us 19 as a result of using this 'ADGJK' path, [11]. H. A. Hamzah, N. Tuah, K. G. Lim, M. K. Tan, L. Zhu
while the Dynamic technique gives us 36 as a result of using and K. T. K. Teo, "Data Transmission in Wireless
this 'ACFIK' path. This is a long path. In this way, we can Sensor Network with Greedy Function and Particle
say that the dynamic technique is best than the greedy Swarm Optimization," 2019 IEEE 7th Conference on
technology. Systems, Process and Control (ICSPC), 2019, pp. 172-
177, doi: 10.1109/ICSPC47137.2019.9068052.
REFERENCES [12]. Djahel, Soufiene&Naït-Abdesselam, Farid & Turgut,
Damla. (2010). An Effective Strategy for Greedy
[1]. K. Lin, P. Wang and T. Hong, "A greedy algorithm in Behavior in Wireless Ad hoc Networks. 1 - 6.
WSNs for maximum network lifetime and 10.1109/GLOCOM.2009.5425412.
communication reliability," 2015 IEEE 12th [13]. Tzu-Chiang, C., Jia-Lin, C., Yue-Fu, T. , Sha-Pai, L..
International Conference on Networking, Sensing and "Greedy Geographical Void Routing for Wireless
Control, 2015, pp. 87-92, doi: Sensor Networks". World Academy of Science,
10.1109/ICNSC.2015.7116015. Engineering and Technology, Open Science Index 78,
[2]. X. Wang, J. Zhao, J. Hou, X. Tang, H. Wu and P. He, International Journal of Computer and Information
"Research on WSN Topology Algorithm Based on Engineering (2013), 7(6), 769 - 777.
Greedy Shortest Paths," 2020 39th Chinese Control
Conference (CCC), 2020, pp. 5215-5220, doi:
10.23919/CCC50068.2020.9189355.
[3]. Seyed Reza Nabavi, NafisehOsatiEraghi, Javad Akbari
Torkestani, "WSN Routing Protocol Using a
Multiobjective Greedy Approach", Wireless
Communications and Mobile Computing, vol. 2021,
Article D 6664669, 12 pages, 2021.
https://doi.org/10.1155/2021/6664669
[4]. "Operation Research Based Techniques in Wireless
Sensors Networks" written by Ahmed RedhaMahlous,
Mohamed Tounsi, published by Communications
and Network, Vol.9 No.1, 2017
[5]. Sadek, F.S.; Belkadi, K.; Abouaissa, A.; Lorenz, P.
Identifying Misbehaving Greedy Nodes in IoT
Networks. Sensors 2021, 21, 5127.
https://doi.org/10.3390/s21155127
[6]. J. P. Mohanty and C. Mandal, "A distributed greedy
algorithm for construction of minimum connected
dominating set in wireless sensor network," 2014
Applications and Innovations in Mobile Computing
(AIMoC), 2014, pp. 104-110, doi:
10.1109/AIMOC.2014.6785527.
[7]. Q. Q. Shi, H. Huo, T. Fang and D. R. Li, "A Modified
Greedy Distance Routing Algorithm for Wireless
Sensor Networks," 2008 China-Japan Joint Microwave
Conference, 2008, pp. 197-200, doi:
10.1109/CJMW.2008.4772405.
[8]. Y. Xin, X. Guang-hua and C. Xiao-jun, "The Research
on Routing Protocol of Sense Wireless Network Based
on the Greedy Algorithm," 2009 International
Conference on Networks Security, Wireless
Communications and Trusted Computing, 2009, pp.
558-561, doi: 10.1109/NSWCTC.2009.159.
[9]. S. Bousnina, M. Cesana, J. Ortín, C. Delgado, J. R.
Gállego and M. Canales, "A greedy approach for
resource allocation in Virtual Sensor Networks," 2017
Wireless Days, 2017, pp. 15-20, doi:
10.1109/WD.2017.7918108.

IJISRT21OCT450 www.ijisrt.com 853

You might also like