diff --git a/Balanced-Unbalanced-exp.py b/Balanced-Unbalanced-exp.py new file mode 100644 index 00000000..a188402e --- /dev/null +++ b/Balanced-Unbalanced-exp.py @@ -0,0 +1,28 @@ +def isBalanced(expr): + stack = [] + for char in expr: + if char in ["(", "{", "["]: + stack.append(char) + else: + if not stack: + return False + current_char = stack.pop() + if current_char == '(': + if char != ")": + return False + if current_char == '{': + if char != "}": + return False + if current_char == '[': + if char != "]": + return False + if stack: + return False + return True + + +expr = input("Enter the Expression i.e. {},[],()- Combination of these\n") +if isBalanced(expr): + print("Balanced") +else: + print("Not Balanced") diff --git a/Python/stable-marriage-pairing.py b/Python/stable-marriage-pairing.py new file mode 100644 index 00000000..cd66e091 --- /dev/null +++ b/Python/stable-marriage-pairing.py @@ -0,0 +1,410 @@ +import random # Used in illustrative text case + +# ---------------------------------------functions------------------------------------ + + +class UnstableTableError(Exception): + """ Error for unstable table when no stable pairings are possible. """ + + +def make_proposals(preferences): + """ Takes in a dictionary with key equal to a participant and + value equal to a list of that participant's preferences. + + Function iterates over each participant in order to find and return + a record of the proposals in the form of a dictionary. + + Each participant proposes in turn using its preference list and + receives a proposal, accepting only the highest preferred + proposal using its preference list and rejecting all others. + + Function returns when there are no longer any participants in the + priority queue (participants left needing to propose) or there are + no more participants to propose to. + + For example: + + Inputs of + preferences = { + 'A': ['B', 'D', 'C'], + 'B': ['D', 'C', 'A'], + 'C': ['A', 'D', 'B'], + 'D': ['A', 'B', 'C'], + } + Outputs => + proposal_record = { + 'A': ['D', 'D'], + 'B': ['C', 'C'], + 'C': ['B', 'B'], + 'D': ['A', 'A'], + } + """ + proposal_record = {} + proposers = [] # using non-optimal list here to represent priority queue + + # Create list of proposers and empty proposal_record for each + for participant in preferences: + proposers.append(participant) + proposal_record[participant] = ["", ""] + + # breakpoint() + # to show proposers and empty proposal_record + + while proposers: + current_proposer = proposers.pop(0) + + # Get current proposer's preference list of proposees + current_proposer_prefs = preferences[current_proposer][:] + + # Propose to each proposee in order until accepted + for proposee in current_proposer_prefs: + proposee_prefs = preferences[proposee] + current_proposer_ranking = proposee_prefs.index(current_proposer) + + # get proposal_record for proposee and proposer + proposee_proposal_to, proposee_proposal_from = proposal_record[proposee] + proposer_proposal_to, proposer_proposal_from = proposal_record[current_proposer] + + # breakpoint() + + # if proposee has not accepted a proposal yet + if not proposee_proposal_from: + proposal_record[proposee][1] = current_proposer + proposal_record[current_proposer][0] = proposee + break + + # if current proposal is better than accepted proposal + elif proposee_prefs.index(proposee_proposal_from) > current_proposer_ranking: + proposal_record[proposee][1] = current_proposer + proposal_record[current_proposer][0] = proposee + + # Reject previously accepted proposal symmetrically + # Step 1: reset rejected participant's proposal record + proposal_record[proposee_proposal_from][0] = "" + # Step 2: put rejected participant at front of priority queue + proposers.insert(0, proposee_proposal_from) + # Step 3: remove rejected pairing symmetrically from the preference list + preferences[proposee].remove(proposee_proposal_from) + preferences[proposee_proposal_from].remove(proposee) + break + + # Otherwise, proposee prefers previously accepted proposal + else: + # Update preference lists for rejected proposal + preferences[proposee].remove(current_proposer) + preferences[current_proposer].remove(proposee) + + return proposal_record + + +def is_stable_table(proposal_record): + """ Function checks if a stable table exists. + Takes in dictionary of lists and iterates over each list. + Checks each list item is not equal to an empty string and + each list pair is unique. + Returns True, if not empty and is unique; otherwise returns False + + Examples Below: + + Stable table: + Inputs of + proposal_record => + { + 'A': ['C', 'B'], + 'B': ['A', 'D'], + 'C': ['D', 'A'], + 'D': ['B', 'C'] + } + Outputs => True + + Unstable table: + Inputs of + proposal_record => + { + 'A': ['D', 'D'], + 'B': ['D', 'A'], + 'C': ['', ''], + 'D': ['A', 'A'] + } + Outputs => False + """ + proposers = set() + proposees = set() + for (proposee, proposer) in proposal_record.values(): + if not proposee or not proposer: + return False + if (proposer in proposers) or (proposee in proposees): + return False + + proposers.add(proposer) + proposees.add(proposee) + + return True + + +def remove_trailing_prefs(proposal_record, preferences): + """ Function trims each preference list by eliminating possibilities indexed + after accepted proposal + Takes in two dictionaries: proposal_record and preference_lists + Returns updated preference_lists + + For example: + Inputs of + proposal_record = { + 'A': ['C', 'B'], - proposed to C and accepted proposal from B + 'B': ['A', 'D'], - proposed to A and accepted proposal from D + 'C': ['D', 'A'], - proposed to D and accepted proposal from A + 'D': ['B', 'C'], - proposed to B and accepted proposal from C + } + preferences = { + 'A': ['C', 'B', 'D'], - remove all prefs that rank lower than B + 'B': ['A', 'C', 'D'], + 'C': ['D', 'B', 'A'], + 'D': ['B', 'A', 'C'], - remove 'A' since 'D' is removed from A's list + } + + Outputs => + preferences = { + 'A': ['C', 'B'], + 'B': ['A', 'C', 'D'], + 'C': ['D', 'B', 'A'], + 'D': ['B', 'C'], + } + """ + for proposer in proposal_record: + proposee = proposal_record[proposer][0] + proposee_prefs = preferences[proposee] + proposer_ranking = proposee_prefs.index(proposer) + + successors = proposee_prefs[proposer_ranking+1:] + + # Updated proposee's preferences, removing successors + preferences[proposee] = proposee_prefs[:proposer_ranking+1] + + # Iterate over successors, deleting proposee from own preference list + for successor in successors: + if proposee in preferences[successor]: + preferences[successor].remove(proposee) + + return preferences + + +def get_stable_match(preferences): + """ Function takes in dictionary of each participant's preferences and + finds stable pairings if it exists by iterating through + participants while preference lists are greater than 1. + Identifies cycles and removes cycle pairs to reduce participant's + preference lists. + + Process is repeated until stable matches are found and preference + lists are length of 1, returning stable pairings + Or, returns UnstableTableError if stable matches are not possible. + + Identify cycles by + - Creating two lists (p and q) until cycle is found in p + p: [participant ],[last item of q0],[last item of q1]... + q: [2nd item of p0],[2nd item of p1 ],[2nd item of p2 ]... + - Creates cycle list to then determine pairs and removes + + For example + Input of + preferences = { + 'A': ['C', 'B'], + 'B': ['A', 'C', 'D'], + 'C': ['D', 'B', 'A'], + 'D': ['B', 'C'] + } + + Identifies cycle: + Starting with 'A' + p = ['A', 'D', 'A'] + q = ['B', 'C',] + Cycle found in p (p[0] == p[2]) + Cycle list = [('D', 'B'), ('A', 'C')] + Pairs removed: ('B', 'C'), ('B', 'D') and ('C', 'A') + Process repeats + + Output => + preferences = {'A': ['B'], 'B': ['A'], 'C': ['D'], 'D': ['C']} + """ + + for participant in preferences: + p = [participant, ] + q = [] + + while len(preferences[participant]) > 1: + def find_cycle(): + new_q = preferences[p[-1]][1] + q.append(new_q) + q_pref_list = preferences[new_q] + new_p = q_pref_list[-1] + + if new_p in p: + p.append(new_p) + return + + p.append(new_p) + find_cycle() + + find_cycle() + + # start at beginning of found cycle, create list representing cycle path + start = p.index(p[-1]) + cycle = [(p[i + 1], q[i]) for i in range(start, len(p) - 1)] + # breakpoint() + + # from cycle path, find pairs to remove + elimination_pairs = find_pairs_to_remove(cycle, preferences) + + try: + preferences = remove_pairs(elimination_pairs, preferences) + except UnstableTableError: + return UnstableTableError + + # reset p and q for next iteration + p = [participant, ] + q = [] + + return preferences + + +def find_pairs_to_remove(cycle, preferences): + """ Find all cycle pairs to remove from each participant's preference lists. + Takes in a list of tuples representing a cycle path found and + dictionary containing each participant's preferences. + Returns list of tuples representing pairs to remove. + + For example: + Input of + cycle = [('D', 'B'), ('A', 'C')] + preferences = { + 'A': ['C', 'B'], + 'B': ['A', 'C', 'D'], + 'C': ['D', 'B', 'A'], + 'D': ['B', 'C'] + } + + where participant = 'B' + participant_prefs = ['A', 'C', 'D'] + first_pref = 'A' + successors = ['C', 'D'] + + Output => + pairs = [('B', 'C'), ('B', 'D'), ('C', 'A')] + """ + pairs = [] + for i, (_, participant) in enumerate(cycle): + # grab the preference list for participant + participant_prefs = preferences[participant] + # first_pref is a pointer for where to start successors list + first_pref = cycle[(i - 1) % len(cycle)][0] + # successors is the tail of the cycle which needs to be removed + successors = participant_prefs[participant_prefs.index( + first_pref) + 1:] + # breakpoint() + + for successor in successors: + pair = (participant, successor) + if pair not in pairs and pair[::-1] not in pairs: + pairs.append((participant, successor)) + return pairs + + +def remove_pairs(pairs, preferences): + """ Takes in list of tuples representing pairs to remove + and dictionary of each participant's preferences. + Returns updated preferences. + + For example: + Input of + pairs = [('B', 'C'), ('B', 'D'), ('C', 'A')] + preferences = { + 'A': ['C', 'B'], + 'B': ['A', 'C', 'D'], + 'C': ['D', 'B', 'A'], + 'D': ['B', 'C'] + } + + Output => + preferences = { + 'A': ['B'], + 'B': ['A'], + 'C': ['D'], + 'D': ['C'] + } + """ + + for (left, right) in pairs: + preferences[left].remove(right) + preferences[right].remove(left) + if not preferences[left] or not preferences[right]: + raise UnstableTableError + + return preferences + + +def find_stable_pairings(preferences): + """ Takes in a dictionary with key equal to a participant and + value equal to a list of preferences + + Returns stable pairing for each participant + + For example: + Input of + preferences = { + "A": ["C", "B", "D"], + "B": ["A", "C", "D"], + "C": ["D", "B", "A"], + "D": ["B", "A", "C"], + } + Output => + preferences_list = { + 'A': ['B'], + 'B': ['A'], + 'C': ['D'], + 'D': ['C'] + } + """ + proposal_record = make_proposals(preferences) + + if not is_stable_table(proposal_record): + return UnstableTableError("No stable pairings possible") + + updated_preferences = remove_trailing_prefs( + proposal_record, + preferences + ) + + try: + print("matching roomates are ") + return get_stable_match(updated_preferences) + except UnstableTableError: + return UnstableTableError("No stable pairings possible") + + +# -------------------------- main code -------------------------- + + +# looping it 30 times so we can get alteast one no stable matching pairings + +for k in range(30): + rithm = {} + N = 6 # we can change here N no of roommates (N is only even) + for i in range(1, N+1): + temp = [] + while len(temp) != N-1: + num = random.randint(1, N) + if num not in temp and num != i: + temp.append(num) + rithm[i] = temp + + i = 0 + j = 0 + for i in range(1, N+1): + print(f"{i} --", end=" ") + for j in range(len(rithm[i])): + print(f"{rithm[i][j]}", end=" ") + print(" ") + + print(find_stable_pairings(rithm)) + print("\n") diff --git a/Python/stable-matching-using-randomization.py b/Python/stable-matching-using-randomization.py new file mode 100644 index 00000000..901d404c --- /dev/null +++ b/Python/stable-matching-using-randomization.py @@ -0,0 +1,840 @@ +# Python3 program for stable marriage problem +import collections +import numpy as np +from random import randrange +import matplotlib.pyplot as plt +import math + + +def calculate(prefer,N,rank): + cnt1=0 + cnt2=0 + cnt3=0 + a=[] + i=0 + for i in range(len(couple)): + if (prefer[N+i][rank]==couple[i]): + cnt1=cnt1+1 + cnt3=cnt3+1 + i=0 + for i in range(len(couple)): + if ((N+i)==prefer[couple[i]][rank]): + cnt2=cnt2+1 + cnt3=cnt3+1 + + return cnt3 + +def calculate2(prefer,N): + cnt1=0 + cnt2=0 + cnt3=0 + a=[] + i=0 + for i in range(len(couple)): + j=0 + for j in range(len(prefer[N+i])): + if (prefer[N+i][j]==couple[i]) and (j<(N/2)): + cnt1=cnt1+1 + cnt3=cnt3+1 + i=0 + for i in range(len(couple)): + j=0 + for j in range(len(prefer[i])): + if ((N+i)==prefer[couple[i]][j]) and (j<(N/2)): + cnt2=cnt2+1 + cnt3=cnt3+1 + + return cnt3 + +def calculate_woman(prefer,N,rank): + cnt1=0 + cnt2=0 + cnt3=0 + a=[] + i=0 + for i in range(len(couple)): + if (prefer[N+i][rank]==couple[i]): + cnt1=cnt1+1 + cnt3=cnt3+1 + + i=0 + for i in range(len(couple)): + if ((N+i)==prefer[couple[i]][rank]): + cnt2=cnt2+1 + cnt3=cnt3+1 + + return cnt1 + +def calculate_man(prefer,N,rank): + cnt1=0 + cnt2=0 + cnt3=0 + a=[] + i=0 + for i in range(len(couple)): + if (prefer[N+i][rank]==couple[i]): + cnt1=cnt1+1 + cnt3=cnt3+1 + + i=0 + for i in range(len(couple)): + if ((N+i)==prefer[couple[i]][rank]): + cnt2=cnt2+1 + cnt3=cnt3+1 + + return cnt2 + +def autolabel(rects): + #................... + for rect in rects: + height = rect.get_height() + ax.annotate('{}'.format(height), + xy=(rect.get_x() + rect.get_width() / 2, height), + xytext=(0, 3), + textcoords="offset points", + ha='center', va='bottom') +def autolabel2(rects): + #................... + for rect in rects: + height = rect.get_height() + ax2.annotate('{}'.format(height), + xy=(rect.get_x() + rect.get_width() / 2, height), + xytext=(0, 3), + textcoords="offset points", + ha='center', va='bottom') + +def wPrefersM1OverM(prefer, w, m, m1,N): + + # Check if w prefers m over her current engagment m1 + i=0 + for i in range(N): + # If m1 comes before m in lisr of w, + # then w prefers her current engagement, don't do anything + if (prefer[w][i] == m1): + return True + + if (prefer[w][i] == m): + return False + +# Prints stable matching for N boys and N girls. +''' +def stableMarriage(prefer,N): + + # Stores partner of women. + wPartner = [-1 for i in range(N)] + + # An array to store availability of men. + # If mFree[i] is false, then man 'i' is free, otherwise engaged. + mFree = [False for i in range(N)] + + freeCount = N + + # While there are free men + while (freeCount > 0): + + # Pick the first free man (we could pick any) + m = 0 + while (m < N): + if (mFree[m] == False): + break + m += 1 + + # One by one go to all women according to + # m's preferences. Here m is the picked free man + i = 0 + while i < N and mFree[m] == False: + w = prefer[m][i] + + # The woman of preference is free, w and m become partners (Note that + # the partnership maybe changed later). So we can say they are engaged not married + if (wPartner[w - N] == -1): + wPartner[w - N] = m + mFree[m] = True + freeCount -= 1 + + else: + + # If w is not free ,Find current engagement of w + m1 = wPartner[w - N] + + # If w prefers m over her current engagement m1, + # then break the engagement between w and m1 and engage m with w. + if (wPrefersM1OverM(prefer, w, m, m1,N) == False): + wPartner[w - N] = m + mFree[m] = True + mFree[m1] = False + i += 1 + + + + # Print couple + for i in range(N): + couple.append(wPartner[i]); + print(i, "\t", wPartner[i]) +''' + +def randomMarriage(prefer,N,k): + n2=int(N/k); + # Stores partner of women. + wPartner = [-1 for i in range(N)] + + # An array to store availability of men. + # If mFree[i] is false, then man 'i' is free, otherwise engaged. + mFree = [False for i in range(N)] + freeCount = N + # While there are free men + while (freeCount > 0): + + # Pick the first free man (we could pick any) + m = 0 + if(freeCount==n2): + break + + # print(f"freecount {freeCount}") + while (m < N): + if (mFree[m] == False): + break + m += 1 + + # One by one go to all women according to + # m's preferences. Here m is the picked free man + i = 0 + while i < N and mFree[m] == False: + w = prefer[m][i] + + # The woman of preference is free, w and m become partners (Note that + # the partnership maybe changed later). So we can say they are engaged not married + if (wPartner[w - N] == -1): + wPartner[w - N] = m + mFree[m] = True + freeCount -= 1 + + else: + + # If w is not free ,Find current engagement of w + m1 = wPartner[w - N] + # If w prefers m over her current engagement m1, + # then break the engagement between w and m1 and engage m with w. + if (wPrefersM1OverM(prefer, w, m, m1,N) == False): + wPartner[w - N] = m + mFree[m] = True + mFree[m1] = False + i += 1 + if(freeCount==n2): + break +#assigning new random................ + + while (freeCount > 0): + + # Pick the first free man (we could pick any) + m = 0 + while (m < N): + if (mFree[m] == False): + break + m += 1 + + # One by one go to all women according to + # m's preferences. Here m is the picked free man + + while mFree[m] == False: + x=randrange(N) + #print(f"random {x} free count {freeCount} ") + w = prefer[m][x] + # The woman of preference is free, w and m become partners (Note that + # the partnership maybe changed later). So we can say they are engaged not married + if (wPartner[w - N] == -1): + wPartner[w - N] = m + mFree[m] = True + freeCount -= 1 + + # Print couple + i=0 + for i in range(N): + couple.append(wPartner[i]); + #print(i, "\t", wPartner[i]) +# Driver Code for +######################################################################## +v=[] +v.append(5) +v.append(10) +v.append(50) +v.append(100) +v.append(200) +v.append(500) +bardata3=[] +bardata=[] +couple=[] +gh=0 +for gh in range(len(v)): + #print(f"{v[gh]} is number of women or men (equal no of man and woman)") + N=v[gh] + prefer=[] + prefer2=[] + man=[] + woman=[] + + #print("enter men's priority") + i=0 + for i in range(N): + a=[] + b=[] + # print(f"the {i} men priority ") + b=np.random.permutation(N) + j=0 + for j in range(len(b)): + a.append(b[j]+N) + prefer.append(a) + man.append(b) + +#print("enter women's priority") + i=0 + for i in range(N): + a =[] + #print(f" the {i} women priority ") + a=np.random.permutation(N) + prefer.append(a) + woman.append(a) + + ''' + print("men's priority") + i=0 + for i in range(0,N): + j=0 + for j in range(len(prefer[i])): + print(prefer[i][j]-N, end = " ") + print() + + print("women's priority ") + i=0 + for i in range(N,2*N): + j=0 + for j in range(len(prefer[i])): + print(prefer[i][j], end = " ") + print() + + #print("Woman ", " Man") + ''' + couple.clear() + i=0 + c1=0 + c2=0 + c3=0 + c4=0 + c11=0 + c22=0 + c33=0 + c44=0 + + for i in range(100): + #print("Zero random ") + randomMarriage(prefer,N,N+1) + c1=c1+calculate_woman(prefer,N,0) + c11=c11+calculate_man(prefer,N,0) + #print(couple) + #print(f" c1 {c1}") + couple.clear() + #print("Half random ") + randomMarriage(prefer,N,2) + c2=c2+calculate_woman(prefer,N,0) + c22=c22+calculate_man(prefer,N,0) + #print(couple) + #print(f" c2 {c2}") + couple.clear() + #print("1/3rd random ") + randomMarriage(prefer,N,3) + c3=c3+calculate_woman(prefer,N,0) + c33=c33+calculate_man(prefer,N,0) + #print(couple) + #print(f" c3 {c3}") + couple.clear() + #print("full random ") + randomMarriage(prefer,N,1) + c4=c4+calculate_woman(prefer,N,0) + c44=c44+calculate_man(prefer,N,0) + #print(couple) + #print(f" c4 {c4}") + couple.clear() + #print(f"{c1} {c2} {c3} {c4} c4---\n") + #print(f"{c11} {c22} {c33} {c44} c44--\n") + + + #print(f"{c1} {c2} {c3} {c4} women data\n") + #print(f"{c11} {c22} {c33} {c44} men data\n") + c1=math.ceil(c1/100) + c2=math.ceil(c2/100) + c3=math.ceil(c3/100) + c4=math.ceil(c4/100) + + c11=math.ceil(c11/100) + c22=math.ceil(c22/100) + c33=math.ceil(c33/100) + c44=math.ceil(c44/100) + + a=[] + b=[] + + a.append(c1) + a.append(c2) + a.append(c3) + a.append(c4) + + b.append(c11) + b.append(c22) + b.append(c33) + b.append(c44) + + #print(a) + #print(b) + bardata.append(a) + bardata3.append(b) + + + +bardata2=[] +bardata22=[] + +j=0 +for j in range(4): + ent=[] + ent2=[] + i=0 + for i in range(len(v)): + ent.append(bardata[i][j]) + ent2.append(bardata3[i][j]) + #print(bardata[i][j],end=" ") + bardata2.append(ent) + bardata22.append(ent2) + +print(" BAR DATA FOR WOMEN FIRST PREFERENCE \n") +i=0 +for i in range(len(bardata2)): + j=0 + for j in range(len(bardata2[i])): + print(bardata2[i][j],end=" ") + print("\n") + +print(" BAR DATA FOR MEN FIRST PREFERENCE \n") +i=0 +for i in range(len(bardata22)): + j=0 + for j in range(len(bardata22[i])): + print(bardata22[i][j],end=" ") + print("\n") + + +labels=[] +i=0 +for i in range(len(v)): + labels.append(str(v[i])) + #print(v[i],end=" ") + +# Add some text for labels, title and custom x-axis tick labels, etc. +x = np.arange(len(labels)) # the label locations +width = 0.20 # the width of the bars +fig, ax = plt.subplots() +rects1 = ax.bar(x +0.10, bardata2[0], width, label='DAA') +rects2 = ax.bar(x +0.30, bardata2[1], width, label='Half Random') +rects3 = ax.bar(x +0.50, bardata2[2], width, label='1/3rd Random') +rects4 = ax.bar(x +0.70, bardata2[3], width, label='Full Random') +# Add some text for labels, title and custom x-axis tick labels, etc. +ax.set_xlabel('NO OF WOMAN') +ax.set_ylabel('NO OF WOMAN GETTING THEIR FIRST PREFERENCE ') +ax.set_title('COMPARISON FOR DIFFERENT SETS OF DATA') +ax.set_xticks(x) +ax.set_xticklabels(labels) +ax.legend() +autolabel(rects1) +autolabel(rects2) +autolabel(rects3) +autolabel(rects4) +fig.tight_layout() +#bardat for womaan +#plt.show() +#bardata for man..... + +labels2=[] +i=0 +for i in range(len(v)): + labels2.append(str(v[i])) + #print(v[i],end=" ") + + +# Add some text for labels, title and custom x-axis tick labels, etc. +x2 = np.arange(len(labels2)) # the label locations +width = 0.20 # the width of the bars +fig2, ax2 = plt.subplots() +rects11 = ax2.bar(x2 +0.10, bardata22[0], width, label='Zero Random') +rects22 = ax2.bar(x2 +0.30, bardata22[1], width, label='Half Random') +rects33 = ax2.bar(x2 +0.50, bardata22[2], width, label='1/3rd Random') +rects44 = ax2.bar(x2 +0.70, bardata22[3], width, label='Full Random') +# Add some text for labels, title and custom x-axis tick labels, etc. +ax2.set_xlabel('NO OF MAN') +ax2.set_ylabel('NO OF MAN GETTING THEIR FIRST PREFERENCE') +ax2.set_title('COMPARISON FOR DIFFERENT SETS OF DATA') +ax2.set_xticks(x) +ax2.set_xticklabels(labels2) +ax2.legend() +autolabel2(rects11) +autolabel2(rects22) +autolabel2(rects33) +autolabel2(rects44) +fig2.tight_layout() +#plt.show() + +############################################################ +''' +print("NEW ALGOOOOOOOOOOOOOOOOO") +''' +for gh in range(4): + N=10 + c1=0 + c2=0 + c3=0 + c4=0 + c5=0 + c6=0 + c7=0 + c11=0 + c22=0 + c33=0 + c44=0 + c55=0 + c66=0 + c77=0 + couple=[] + #print(f"{N} is number of women or men (equal no of man and woman)") + prefer=[] + prefer2=[] + man=[] + woman=[] + bardata2=[] + + #print("enter men's priority") + + for i in range(N): + a =[] + b=[] + # print(f"the {i} men priority ") + b=np.random.permutation(N) + for j in range(len(b)): + a.append(b[j]+N) + prefer.append(a) + man.append(b) + +#print("enter women's priority") + + for i in range(N): + a =[] + #print(f" the {i} women priority ") + a=np.random.permutation(N) + prefer.append(a) + woman.append(a) + ''' + print("men's priority") + + for i in range(0,N): + for j in range(len(prefer[i])): + print(prefer[i][j]-N, end = " ") + print() + + print("women's priority ") + + for i in range(N,2*N): + for j in range(len(prefer[i])): + print(prefer[i][j], end = " ") + print() + ''' + if gh==0: + for zx in range(100): + couple=[] + randomMarriage(prefer,N,N+1) + c11=c11+calculate(prefer,N,0) + c22=c22+calculate(prefer,N,1) + c33=c33+calculate(prefer,N,2) + c44=c44+calculate(prefer,N,3) + c55=c55+calculate(prefer,N,4) + c66=c66+calculate(prefer,N,N-1) + c77=c77+calculate2(prefer,N) + + c1=math.ceil(c11/100) + c2=math.ceil(c22/100) + c3=math.ceil(c33/100) + c4=math.ceil(c44/100) + c5=math.ceil(c55/100) + c6=math.ceil(c66/100) + c7=math.ceil(c77/100) + + bardata=[] + bardata2=[] + bardata.append(c1) + bardata.append(c2) + bardata.append(c3) + bardata.append(c4) + bardata.append(c5) + bardata.append(c6) + bardata.append(c7) + bardata2.append(bardata) + labels=[] + labels.append(str(1)) + labels.append(str(2)) + labels.append(str(3)) + labels.append(str(4)) + labels.append(str(5)) + labels.append("LAST") + labels.append("FIRST HALF") + print(" BAR DATA FOR DAA FOR FIRST SECOND UPTO HALF AND LAST \n") + i=0 + for i in range(len(bardata2)): + j=0 + for j in range(len(bardata2[i])): + print(bardata2[i][j],end=" ") + print("\n") + +# Add some text for labels, title and custom x-axis tick labels, etc. + x = np.arange(len(labels)) # the label locations + width = 0.20 # the width of the bars + fig, ax = plt.subplots() + rects1 = ax.bar(x +0.10, bardata2[0], width, label='DAA') +# Add some text for labels, title and custom x-axis tick labels, etc. + ax.set_xlabel('PREFERENCE') + ax.set_ylabel('NO OF PEOPLE') + ax.set_title('COMPARISON FOR DIFFERENT SETS OF DATA') + ax.set_xticks(x) + ax.set_xticklabels(labels) + ax.legend() + autolabel(rects1) + fig.tight_layout() + #plt.show() + + if gh==1: + for zx in range(100): + couple=[] + randomMarriage(prefer,N,2) + c11=c11+calculate(prefer,N,0) + c22=c22+calculate(prefer,N,1) + c33=c33+calculate(prefer,N,2) + c44=c44+calculate(prefer,N,3) + c55=c55+calculate(prefer,N,4) + c66=c66+calculate(prefer,N,N-1) + c77=c77+calculate2(prefer,N) + + + c1=math.ceil(c11/100) + c2=math.ceil(c22/100) + c3=math.ceil(c33/100) + c4=math.ceil(c44/100) + c5=math.ceil(c55/100) + c6=math.ceil(c66/100) + c7=math.ceil(c77/100) + + bardata2=[] + bardata=[] + bardata.append(c1) + bardata.append(c2) + bardata.append(c3) + bardata.append(c4) + bardata.append(c5) + bardata.append(c6) + bardata.append(c7) + bardata2.append(bardata) + labels=[] + labels.append(str(1)) + labels.append(str(2)) + labels.append(str(3)) + labels.append(str(4)) + labels.append(str(5)) + labels.append("LAST") + labels.append("FIRST HALF") + print(" BAR DATA FOR HALF RANDOM FOR FIRST SECOND UPTO HALF AND LAST \n") + + i=0 + for i in range(len(bardata2)): + j=0 + for j in range(len(bardata2[i])): + print(bardata2[i][j],end=" ") + print("\n") +# Add some text for labels, title and custom x-axis tick labels, etc. + x = np.arange(len(labels)) # the label locations + width = 0.20 # the width of the bars + fig, ax = plt.subplots() + rects1 = ax.bar(x +0.10, bardata2[0], width, label='Half Random') +# Add some text for labels, title and custom x-axis tick labels, etc. + ax.set_xlabel('PREFERENCE') + ax.set_ylabel('NO OF PEOPLE') + ax.set_title('COMPARISON FOR DIFFERENT SETS OF DATA') + ax.set_xticks(x) + ax.set_xticklabels(labels) + ax.legend() + autolabel(rects1) + fig.tight_layout() + #plt.show() + if gh==2: + couple=[] + for zx in range(100): + couple=[] + randomMarriage(prefer,N,3) + c11=c11+calculate(prefer,N,0) + c22=c22+calculate(prefer,N,1) + c33=c33+calculate(prefer,N,2) + c44=c44+calculate(prefer,N,3) + c55=c55+calculate(prefer,N,4) + c66=c66+calculate(prefer,N,N-1) + c77=c77+calculate2(prefer,N) + + + c1=math.ceil(c11/100) + c2=math.ceil(c22/100) + c3=math.ceil(c33/100) + c4=math.ceil(c44/100) + c5=math.ceil(c55/100) + c6=math.ceil(c66/100) + c7=math.ceil(c77/100) + + bardata=[] + bardata.append(c1) + bardata.append(c2) + bardata.append(c3) + bardata.append(c4) + bardata.append(c5) + bardata.append(c6) + bardata.append(c7) + bardata2.append(bardata) + labels=[] + labels.append(str(1)) + labels.append(str(2)) + labels.append(str(3)) + labels.append(str(4)) + labels.append(str(5)) + labels.append("LAST") + labels.append("FIRST HALF") + print(" BAR DATA FOR 1/3RD RANDOM FOR FIRST SECOND UPTO HALF AND LAST \n") + + i=0 + for i in range(len(bardata2)): + j=0 + for j in range(len(bardata2[i])): + print(bardata2[i][j],end=" ") + print("\n") + +# Add some text for labels, title and custom x-axis tick labels, etc. + x = np.arange(len(labels)) # the label locations + width = 0.20 # the width of the bars + fig, ax = plt.subplots() + rects1 = ax.bar(x +0.10, bardata2[0], width, label='1/3rd Random') +# Add some text for labels, title and custom x-axis tick labels, etc. + ax.set_xlabel('PREFERENCE') + ax.set_ylabel('NO OF PEOPLE') + ax.set_title('COMPARISON FOR DIFFERENT SETS OF DATA') + ax.set_xticks(x) + ax.set_xticklabels(labels) + ax.legend() + autolabel(rects1) + fig.tight_layout() + #plt.show() + + if gh==3: + couple=[] + for zx in range(100): + couple=[] + randomMarriage(prefer,N,1) + c11=c11+calculate(prefer,N,0) + c22=c22+calculate(prefer,N,1) + c33=c33+calculate(prefer,N,2) + c44=c44+calculate(prefer,N,3) + c55=c55+calculate(prefer,N,4) + c66=c66+calculate(prefer,N,N-1) + c77=c77+calculate2(prefer,N) + + + c1=math.ceil(c11/100) + c2=math.ceil(c22/100) + c3=math.ceil(c33/100) + c4=math.ceil(c44/100) + c5=math.ceil(c55/100) + c6=math.ceil(c66/100) + c7=math.ceil(c77/100) + + bardata=[] + bardata2=[] + bardata.append(c1) + bardata.append(c2) + bardata.append(c3) + bardata.append(c4) + bardata.append(c5) + bardata.append(c6) + bardata.append(c7) + bardata2.append(bardata) + labels=[] + labels.append(str(1)) + labels.append(str(2)) + labels.append(str(3)) + labels.append(str(4)) + labels.append(str(5)) + labels.append("LAST") + labels.append("FIRST HALF") + print(" BAR DATA FOR FULL RANDOM FOR FIRST SECOND UPTO HALF AND LAST \n") + + i=0 + for i in range(len(bardata2)): + j=0 + for j in range(len(bardata2[i])): + print(bardata2[i][j],end=" ") + print("\n") + +# Add some text for labels, title and custom x-axis tick labels, etc. + x = np.arange(len(labels)) # the label locations + width = 0.20 # the width of the bars + fig, ax = plt.subplots() + rects1 = ax.bar(x +0.10, bardata2[0], width, label='Full Random') +# Add some text for labels, title and custom x-axis tick labels, etc. + ax.set_xlabel('PREFERENCE') + ax.set_ylabel('NO OF PEOPLE') + ax.set_title('COMPARISON FOR DIFFERENT SETS OF DATA') + ax.set_xticks(x) + ax.set_xticklabels(labels) + ax.legend() + autolabel(rects1) + fig.tight_layout() + #plt.show() +plt.show() + + + + + + +############################################################# +''' for assigning from second side (woman side )............ +print("...FOR SECOND TURN ...") + + +for i in range(N): + a=[] + for j in range(len(woman[i])): + a.append(woman[i][j]+N) + prefer2.append(a) + +for i in range(N): + a=[] + for j in range(len(man[i])): + a.append(man[i][j]) + prefer2.append(a) + +print("women's priority ") +for i in range(0,N): + for j in range(len(prefer2[i])): + print(prefer2[i][j]-N,end = " ") + print() + +print("man's priority ") +for i in range(N,2*N): + for j in range(len(prefer2[i])): + print(prefer2[i][j], end = " ") + print() + +print("Man ", "Woman") +stableMarriage(prefer2,N) +''' + + + diff --git a/fact-og-large-number.cpp b/fact-og-large-number.cpp new file mode 100644 index 00000000..d05dee48 --- /dev/null +++ b/fact-og-large-number.cpp @@ -0,0 +1,48 @@ +#include +using namespace std; + +#define MAX 500 + +int multiply(int x, int res[], int res_size); + +void factorial(int n) +{ + int res[MAX]; + + res[0] = 1; + int res_size = 1; + + for (int x=2; x<=n; x++) + res_size = multiply(x, res, res_size); + + cout << "Factorial of given number is \n"; + for (int i=res_size-1; i>=0; i--) + cout << res[i]; +} + int multiply(int x, int res[], int res_size) +{ + int carry = 0; // Initialize carry + + for (int i=0; i>n; +factorial(n); + return 0; +} diff --git a/searcharray.cpp b/searcharray.cpp new file mode 100644 index 00000000..1d214aa5 --- /dev/null +++ b/searcharray.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; + +int main(){ +int n; +cout<<"Enter size of the array:"<>n; +int arr[n]; +cout<<"Enter array elements:"<>arr[i]; +int x; +cout<<"Enter number to be found:"<>x; +//search +for(int i=0;i