Foros del Web » Programación para mayores de 30 ;) » Java »

Algoritmo Round Robin en Java

Estas en el tema de Algoritmo Round Robin en Java en el foro de Java en Foros del Web. hola a todos quisiera saber si alguien tiene el codigo java para el algoritmo Roun Robin. Lo que necesito es: Tengo a los id de ...
  #1 (permalink)  
Antiguo 02/06/2009, 09:17
 
Fecha de Ingreso: mayo-2009
Mensajes: 3
Antigüedad: 15 años
Puntos: 0
Algoritmo Round Robin en Java

hola a todos quisiera saber si alguien tiene el codigo java para el algoritmo Roun Robin.

Lo que necesito es:


Tengo a los id de n participantes en una competencia de artes marciales, guardados en un arreglo y cada uno de ellos debe de pelear contra los otros entonces el numero de peleas es n-1.


el algoritmo round robin me parece el mejor pero aun no lo entiendo muy bien, encontre un codigo en Phyton pero no lo comprendo por q no se ese lenguaje . Lo dejo aqui por si alguien me puede ayudar, de antemano muchas gracias !!!

Using generators instead of simply returning lists or tuples has the
advantage that we do not eat up so much memory at once.
Properties and the possibility to define our own __iter__ function provide nice
ways to create very simple interfaces to Python classes. And Python's overall
compactness makes it possible to do all our work with very few lines of code.

Example usage:

from roundrobin import RoundRobin

# Just passing a list or a tuple would work as well,
# but a set makes sure that we do not pass any duplicate
# players.
players = set(['foo', 'bar', 'baz'])

rr = RoundRobin(players)
for game in rr:
print "%s vs %s" % (game[0], game[1])

Or:

from roundrobin import RoundRobin

players = set(['foo', 'bar', 'baz'])

round_n, game_n = 0, 0
for round in rr.rounds:
round_n += 1
print "Round #", round_n
for game in round:
game_n += 1
print " Game #%d: %s vs %s" % (game_n, game[0], game[1])

As an exercise, one could try to add the following feature:
Consider the first element of each game tuple to be the home player
and try to balance the number of home/away matches as far as possible.
"""

class RoundRobin(object):
def __init__(self, players):
if None in players:
raise ValueError("None is not a valid player")
# Create two lists from the player set.
# One of them is a constant needed for self-reinitialization,
# the other one is a working copy that is going to be modified.
self._players = list(players)
self._PLAYERS = list(players)
# Insert a dummy player if necessary.
if len(self._players) % 2 != 0:
self._players.append(None)
self._in_firstround = True

def __iter__(self):
# Generator to iterate over all games.
while self._nextRound():
for game in self._getRound():
yield game

def _getRounds(self):
# Generator to iterate over all rounds.
while self._nextRound():
yield [game for game in self._getRound()]
rounds = property(_getRounds)

def _getRound(self):
# Generator to iterate over the games for the *current* round.
games = []
for i in range(len(self._players) / 2):
# First vs last, second vs second last, etc.
p1, p2 = self._players[i], self._players[(-i)-1]
# None is the dummy player: None's opponent does not play.
if not None in (p1, p2):
yield (p1, p2)

def _nextRound(self):
if self._players[1] != self._PLAYERS[1] or self._in_firstround:
# The first player is fixed, all others are shifted one position
# to the right, the rightmost one is wrapped around and becomes
# the new second one.
nonfixed = self._players[1:]
self._players = [self._players[0]] + nonfixed[-1:] + nonfixed[:-1]
self._in_firstround = False
return True
else:
# The original second player is on position 2 and we are not in
# the first round: we have shifted around once.
# Time to re-initialize ourselves.
self.__init__(self._PLAYERS)
return False
  #2 (permalink)  
Antiguo 02/06/2009, 11:02
 
Fecha de Ingreso: octubre-2003
Mensajes: 3.578
Antigüedad: 20 años, 6 meses
Puntos: 51
Respuesta: Algoritmo Round Robin en Java

Lo primero que debes hacer es entender lo que es el concepto de RoundRobin, aunque no entiendo bien a que viene en este caso por que si tienen que luchar contra todos, da igual como lo hagas. Yo creo que antes de obsesionarte en implementar un algoritmo que no entiendes, deberías concentrarte en solucionar tu problema, que quizás sea más fácil de lo que te parece.

Lo segundo es.. ¿has pensado que has puesto un codigo Python de ejemplo en un foro de "expertos" en Java?

S!
__________________
Para obtener respuestas, pregunta de forma inteligente o si no, pregunta lo que quieras que yo contestaré lo que me dé la gana.
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 00:05.