GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — coding-problems/Arrays/secret_santa.py at master · arjunkumar09/coding-problems

Expand file tree

/

secret_santa.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
58 lines (42 loc) · 1.54 KB
/

secret_santa.py

Copy path

File metadata and controls

58 lines (42 loc) · 1.54 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
'''
Secret Santa
Secret Santa is a game in which a group of friends or colleagues exchange Christmas presents anonymously,
each member of the group being assigned another member for whom to provide a small gift.
You're given a list of names, make a random pairs (each participant should have another name as pair).
Return an array with pairs represented as tuples.
Input: ['a', 'b', 'c']
Output: This is a nondeterministic algorithm, more solutions exists, here are 2 possible solutions:
[('a', 'b'), ('b', 'c'), ('c', 'a')], [('a', 'c'), ('c', 'b'), ('b', 'a')]
=========================================
Shuffle the array (this algorithm is explained in shuffle_array.py) and pair the current element
with the next element (neighbouring).
Time Complexity: O(N)
Space Complexity: O(N)
'''
############
# Solution #
############
from random import randint
def secret_santa(names):
# or use shuffle method from random module (from random import shuffle)
shuffle_array(names)
pairs = []
n = len(names)
prev = names[-1] # or names[n - 1]
for curr in names:
pairs.append((prev, curr))
prev = curr
return pairs
def shuffle_array(arr):
n = len(arr)
for i in range(n):
rand = randint(i, n - 1) # or randint(0, i) it's same
arr[i], arr[rand] = arr[rand], arr[i] # swap elements
# the original arr is already changed
return arr
###########
# Testing #
###########
# Test 1
# Correct result => nondeterministic algorithm, many solutions exist
print(secret_santa(['a', 'b', 'c']))
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.