Skip to content

Instantly share code, notes, and snippets.

@raarce
Last active November 16, 2016 17:34
Show Gist options
  • Save raarce/f246f52cf678d73ff20e465861213e7d to your computer and use it in GitHub Desktop.
Save raarce/f246f52cf678d73ff20e465861213e7d to your computer and use it in GitHub Desktop.
'''
Example file:
@name
rafa
qwer
mari
guil
@pref
qwer rafa mari
guil mari
@avoid
name: diccionario de key=nombre, value=indice
prefList: diccionario de key:indice, value:lista de indices que prifiere
'''
# Read the file
f = open('data.txt', "r")
f = f.read().split('\n')
# Status: -1=starting, 0=reading names, 2=reading prefs, 4=reading avoid
status = -1
name = {}
prefList = {}
avoidList = {}
# Contruir los diccionarios en base al contenido del file
for line in f:
if status == -1 and line == '@name':
status = 0
nameCtr = 0
elif status == 0:
if line == '@pref':
status = 2
else:
if line in name:
status = -2
else:
name[line] = nameCtr
nameCtr += 1
elif status == 2:
if line == '@avoid':
status = 4
else:
L = line.split(" ")
thisName = L[0]
prefList[name[thisName]] = []
for i in L[1:]:
prefList[name[L[0]]].append(name[i])
elif status == 4 and len(line) > 2:
L = line.split(" ")
thisName = L[0]
avoidList[name[thisName]] = []
for i in L[1:]:
avoidList[name[L[0]]].append(name[i])
else:
print "Some error occurred"
# Completar el arreglo de preferencias usando los match y los avoid.
dontCare = {}
complete = {}
nameReverse = {}
for n in name: nameReverse[name[n]] = n
print "names:", name
print "nameReverse:", nameReverse
print "prefList:", prefList
print "avoidList:",avoidList
# Para cada nombre construir la lista de los dont cares, i.e. aquellos indices
# que no esten en los match ni en los avoid
for n in name:
nameIdx = name[n]
pref = None
avoid = None
if nameIdx in prefList: pref = prefList[nameIdx]
if nameIdx in avoidList: avoid = avoidList[nameIdx]
dontCare[nameIdx] = []
for i in range(nameCtr):
if not ((pref != None and i in pref) or (avoid != None and i in avoid) or (i == nameIdx)) :
dontCare[nameIdx].append(i)
if pref == None: pref = []
if avoid == None: avoid = []
random.shuffle(dontCare[nameIdx])
complete[nameIdx] = pref + dontCare[nameIdx] + avoid
print complete
Z = []
for i in range(nameCtr-1):
for j in range(nameCtr):
Z.append(complete[j][i]+1)
nameList = []
for i in range(nameCtr):
nameList.append("\"" + nameReverse[i] + "\"")
print '\n------run this in R-----------\n'
print 'library(matchingR)'
print 'names <- c(%s)' % ','.join(nameList)
print 'pref = matrix (c(%s), nrow=%d, ncol=%d, byrow=TRUE)' % ( ','.join(map(str, Z)), nameCtr-1, nameCtr)
print 'roommate.checkPreferences(pref)'
print 'results = roommate(pref = pref)'
print 'results'
print 'for (i in 1:length(results)) '
print '\tcat(names[i], " - " , names[results[i]], "\\n")'
print '\n----------------------------\n'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment