Initial Commit

This commit is contained in:
Caleb Braaten 2024-04-16 02:50:37 -07:00
commit 513a05f5f7
23 changed files with 1990 additions and 0 deletions

View File

@ -0,0 +1,64 @@
Braille Translation
===================
Because Commander Lambda is an equal-opportunity despot, she has several visually-impaired minions. But she never bothered to follow intergalactic standards for workplace accommodations, so those minions have a hard time navigating her space station. You figure printing out Braille signs will help them, and - since you'll be promoting efficiency at the same time - increase your chances of a promotion.
Braille is a writing system used to read by touch instead of by sight. Each character is composed of 6 dots in a 2x3 grid, where each dot can either be a bump or be flat (no bump). You plan to translate the signs around the space station to Braille so that the minions under Commander Lambda's command can feel the bumps on the signs and ""read"" the text with their touch. The special printer which can print the bumps onto the signs expects the dots in the following order:
1 4
2 5
3 6
So given the plain text word ""code"", you get the Braille dots:
11 10 11 10
00 01 01 01
00 10 00 00
where 1 represents a bump and 0 represents no bump. Put together, ""code"" becomes the output string ""100100101010100110100010"".
Write a function solution(plaintext) that takes a string parameter and returns a string of 1's and 0's representing the bumps and absence of bumps in the input string. Your function should be able to encode the 26 lowercase letters, handle capital letters by adding a Braille capitalization mark before that character, and use a blank character (000000) for spaces. All signs on the space station are less than fifty characters long and use only letters and spaces.
Languages
=========
To provide a Python solution, edit solution.py
To provide a Java solution, edit Solution.java
Test cases
==========
Your code should pass the following test cases.
Note that it may also be run against hidden test cases not shown here.
-- Python cases --
Input:
solution.solution("code")
Output:
100100101010100110100010
Input:
solution.solution("Braille")
Output:
000001110000111010100000010100111000111000100010
Input:
solution.solution("The quick brown fox jumps over the lazy dog")
Output:
000001011110110010100010000000111110101001010100100100101000000000110000111010101010010111101110000000110100101010101101000000010110101001101100111100011100000000101010111001100010111010000000011110110010100010000000111000100000101011101111000000100110101010110110
-- Java cases --
Input:
Solution.solution("code")
Output:
100100101010100110100010
Input:
Solution.solution("Braille")
Output:
000001110000111010100000010100111000111000100010
Input:
Solution.solution("The quick brown fox jumps over the lazy dog")
Output:
000001011110110010100010000000111110101001010100100100101000000000110000111010101010010111101110000000110100101010101101000000010110101001101100111100011100000000101010111001100010111010000000011110110010100010000000111000100000101011101111000000100110101010110110
Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder.

View File

@ -0,0 +1,48 @@
def solution(s):
answer = ""
braille = {
" ": "000000",
"a": "100000",
"b": "110000",
"c": "100100",
"d": "100110",
"e": "100010",
"f": "110100",
"g": "110110",
"h": "110010",
"i": "010100",
"j": "010110",
"k": "101000",
"l": "111000",
"m": "101100",
"n": "101110",
"o": "101010",
"p": "111100",
"q": "111110",
"r": "111010",
"s": "011100",
"t": "011110",
"u": "101001",
"v": "111001",
"w": "010111",
"x": "101101",
"y": "101111",
"z": "101011"
}
for letter in s:
if letter.isupper():
answer += "000001" + braille[letter.lower()]
else:
answer += braille[letter]
return answer
if solution("code") == "100100101010100110100010":
print("case1: passed")
if solution("Braille") == "000001110000111010100000010100111000111000100010":
print("case2: passed")
if solution("The quick brown fox jumps over the lazy dog") == "000001011110110010100010000000111110101001010100100100101000000000110000111010101010010111101110000000110100101010101101000000010110101001101100111100011100000000101010111001100010111010000000011110110010100010000000111000100000101011101111000000100110101010110110":
print("case3: passed")

View File

@ -0,0 +1,52 @@
Bunny Prisoner Locating
=======================
Keeping track of Commander Lambda's many bunny prisoners is starting to get tricky. You've been tasked with writing a program to match bunny prisoner IDs to cell locations.
The LAMBCHOP doomsday device takes up much of the interior of Commander Lambda's space station, and as a result the prison blocks have an unusual layout. They are stacked in a triangular shape, and the bunny prisoners are given numerical IDs starting from the corner, as follows:
| 7
| 4 8
| 2 5 9
| 1 3 6 10
Each cell can be represented as points (x, y), with x being the distance from the vertical wall, and y being the height from the ground.
For example, the bunny prisoner at (1, 1) has ID 1, the bunny prisoner at (3, 2) has ID 9, and the bunny prisoner at (2,3) has ID 8. This pattern of numbering continues indefinitely (Commander Lambda has been taking a LOT of prisoners).
Write a function solution(x, y) which returns the prisoner ID of the bunny at location (x, y). Each value of x and y will be at least 1 and no greater than 100,000. Since the prisoner ID can be very large, return your solution as a string representation of the number.
Languages
=========
To provide a Java solution, edit Solution.java
To provide a Python solution, edit solution.py
Test cases
==========
Your code should pass the following test cases.
Note that it may also be run against hidden test cases not shown here.
-- Java cases --
Input:
Solution.solution(3, 2)
Output:
9
Input:
Solution.solution(5, 10)
Output:
96
-- Python cases --
Input:
solution.solution(5, 10)
Output:
96
Input:
solution.solution(3, 2)
Output:
9
Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder.

View File

@ -0,0 +1,20 @@
def solution(x, y):
prisonerID = 0
#traverse down the x axis first
i = x
while i > 0:
prisonerID += i
i -= 1
#traverse up the y axis second
while y > 1:
prisonerID += x
x += 1
y -= 1
#return the string of the id
return str(prisonerID)
print "Case 1,1: " + solution(1,1)

View File

@ -0,0 +1,43 @@
def solution(xs):
# Set initial values (ignore any leading zeros)
startPoint = next((index for index, value in enumerate(xs) if value != 0), None)
maxCap = xs[startPoint]
smallestNegative = -9223372036854775808 # Largest Negative Starting Value
# Test edge case of just one item in the array
try:
xs[startPoint+1]
except IndexError:
return str(xs[0])
# One time check to see if maxCap contains a negative value
if maxCap > smallestNegative and maxCap < 0:
smallestNegative = maxCap
# Loop through the rest of array
for item in xs[startPoint+1:]:
if item > smallestNegative and item < 0:
smallestNegative = item
if item != 0:
maxCap *= item
# If the value ends on negative - undo the smallest multipication for the biggest number
if maxCap < 0:
maxCap /= smallestNegative
return str(maxCap)
case1 = int(solution([0,0,0,0,2,0,2,2,0])) # 8
# case2 = int(solution([0,-2,-3,4,-5])) # 60
if case1 == 8:
print "Test 1: Passed"
else:
print "Test 1: Failed"
print "Recieved " + str(case1)
# if case2 == 60:
# print "Test 2: Passed"
# else:
# print "Test 2: Failed"
# print "Recieved " + str(case2)

View File

@ -0,0 +1,27 @@
def solution(xs):
# Test edge case of just one array value
try:
xs[1]
except IndexError:
return str(xs[0])
# Set initial values
maxCap = xs[0]
smallestNegative = -9223372036854775808 # Largest Negative Starting Value
# One time check to see if maxCa[ contains a negative value
if maxCap > smallestNegative and maxCap < 0:
smallestNegative = maxCap
# Loop through the rest of array
for item in xs[1:]:
if item > smallestNegative and item < 0:
smallestNegative = item
if item != 0:
maxCap *= item
# If the value ends on negative - undo the smallest multipication for the biggest number
if maxCap < 0:
maxCap /= smallestNegative
return str(maxCap)

View File

@ -0,0 +1,43 @@
Power Hungry
============
Commander Lambda's space station is HUGE. And huge space stations take a LOT of power. Huge space stations with doomsday devices take even more power. To help meet the station's power needs, Commander Lambda has installed solar panels on the station's outer surface. But the station sits in the middle of a quasar quantum flux field, which wreaks havoc on the solar panels. You and your team of henchmen have been assigned to repair the solar panels, but you'd rather not take down all of the panels at once if you can help it, since they do help power the space station and all!
You need to figure out which sets of panels in any given array you can take offline to repair while still maintaining the maximum amount of power output per array, and to do THAT, you'll first need to figure out what the maximum output of each array actually is. Write a function solution(xs) that takes a list of integers representing the power output levels of each panel in an array, and returns the maximum product of some non-empty subset of those numbers. So for example, if an array contained panels with power output levels of [2, -3, 1, 0, -5], then the maximum product would be found by taking the subset: xs[0] = 2, xs[1] = -3, xs[4] = -5, giving the product 2*(-3)*(-5) = 30. So solution([2,-3,1,0,-5]) will be "30".
Each array of solar panels contains at least 1 and no more than 50 panels, and each panel will have a power output level whose absolute value is no greater than 1000 (some panels are malfunctioning so badly that they're draining energy, but you know a trick with the panels' wave stabilizer that lets you combine two negative-output panels to produce the positive output of the multiple of their power values). The final products may be very large, so give the solution as a string representation of the number.
Languages
=========
To provide a Python solution, edit solution.py
To provide a Java solution, edit Solution.java
Test cases
==========
Your code should pass the following test cases.
Note that it may also be run against hidden test cases not shown here.
-- Python cases --
Input:
solution.solution([2, 0, 2, 2, 0])
Output:
8
Input:
solution.solution([-2, -3, 4, -5])
Output:
60
-- Java cases --
Input:
Solution.solution({2, 0, 2, 2, 0})
Output:
8
Input:
Solution.solution({-2, -3, 4, -5})
Output:
60
Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder.

View File

@ -0,0 +1,71 @@
def solution(xs):
maxCap = 0
smallestNegative = -9223372036854775808 # Largest Negative Starting Value
for item in xs:
# Skip item if 0
if item == 0 or item == -1 or item == 1:
continue
else:
# Record the smallest negative number in the case we need it
if item > smallestNegative and item < 0:
smallestNegative = item
if maxCap == 0:
maxCap = item
else:
# Calculate the actual power
maxCap *= item
# Check if we have a negative max power - if so, undo the smallest negative factor
if maxCap < 0 and smallestNegative != 0:
maxCap /= smallestNegative
return str(maxCap)
case1 = int(solution([2,0,2,2,0])) # 8
case2 = int(solution([-2,-3,4,-5])) # 60
case3 = int(solution([-2,-2,-2,-3,-1])) # 24
case4 = int(solution([-2,-2,-2,-1])) # 4 ... or 8?
case5 = int(solution([1,-2,2,2])) # 4 recieved 4
case6 = int(solution([1,2,2,2])) # 8
if case1 == 8:
print "Test 1: Passed"
else:
print "Test 1: Failed"
print "Recieved " + str(case1)
if case2 == 60:
print "Test 2: Passed"
else:
print "Test 2: Failed"
print "Recieved " + str(case2)
if case3 == 24:
print "Test 3: Passed"
else:
print "Test 3: Failed"
print "Recieved " + str(case3)
if case4 == 4:
print "Test 4: Passed"
else:
print "Test 4: Failed"
print "Recieved " + str(case4)
if case5 == 4:
print "Test 5: Passed"
else:
print "Test 5: Failed"
print "Recieved " + str(case5)
if case6 == 8:
print "Test 6: Passed"
else:
print "Test 6: Failed"
print "Recieved " + str(case6)

View File

@ -0,0 +1,77 @@
def solution(xs):
try:
xs[1]
except IndexError:
return str(xs[0])
maxCap = 0
smallestNegative = -9223372036854775808 # Largest Negative Starting Value
for item in xs:
# Skip item if 0
if item == 1:
continue
else:
# Record the smallest negative number in the case we need it
if item > smallestNegative and item < 0:
smallestNegative = item
if maxCap == 0:
maxCap = item
else:
if item == 0:
continue
else:
maxCap *= item
# Check if we have a negative max power - if so, undo the smallest negative factor
if maxCap < 0:
maxCap /= smallestNegative
return str(maxCap)
case1 = int(solution([2,0,2,2,0])) # 8
case2 = int(solution([-2,-3,4,-5])) # 60
case3 = int(solution([0,2,0])) # 2
case4 = int(solution([0, -2, 2, 0])) # 2
case5 = int(solution([0,0,0,0])) # 0
# case6 = int(solution([-2,-1])) # -2 ... 2
if case1 == 8:
print "Test 1: Passed"
else:
print "Test 1: Failed"
print "Recieved " + str(case1)
if case2 == 60:
print "Test 2: Passed"
else:
print "Test 2: Failed"
print "Recieved " + str(case2)
if case3 == 2:
print "Test 3: Passed"
else:
print "Test 3: Failed"
print "Recieved " + str(case3)
if case4 == 2:
print "Test 4: Passed"
else:
print "Test 4: Failed"
print "Recieved " + str(case4)
if case5 == 0:
print "Test 5: Passed"
else:
print "Test 5: Failed"
print "Recieved " + str(case5)
# if case6 == -2:
# print "Test 6: Passed"
# else:
# print "Test 6: Failed"
# print "Recieved " + str(case6)

View File

@ -0,0 +1,44 @@
def solution(n):
opCounter = 0
pellets = int(n)
if pellets == 0:
return 1
while pellets > 1:
print "Iteration Started w/ " + str(pellets) + " pellets left."
if pellets == 3:
print "Special 3"
pellets -= 1
opCounter += 1
if pellets % 2 == 0:
pellets /= 2
opCounter += 1
print "Divided Pellets by two - operations: " + str(opCounter)
continue
if bitwiseIsPowerTwo(pellets+1) and pellets >= 15:
pellets = (pellets+1)/2
opCounter += 2
print "Power of two fast path - operations: " + str(opCounter)
continue
pellets += 1
opCounter += 1
print "Base case, subtract one - operations: " + str(opCounter)
print "One pellet left - total ops: " + str(opCounter)
return opCounter
def bitwiseIsPowerTwo(n):
return (n != 0) and (n & (n-1) == 0)
case1 = int(solution('372')) # Return 12 # 372 -> 186 -> 93 -> 92 -> 46 -> 23 -> 22 -> 11 -> 10 -> 5 -> 4 -> 2 -> 1
# Return 11 # 372 -> 186 -> 93 -> 94 -> 47 -> 48 -> 24 -> 12 -> 6 -> 3 -> 2 -> 1
if case1 == 11:
print "Test 1: Passed"
else:
print "Test 1: Failed"
print "Recieved " + str(case1)

View File

@ -0,0 +1,81 @@
# Return true or false on if the number is a power of two
def bitwiseIsPowerTwo(n):
return (n != 0) and (n & (n-1) == 0)
# solution(1) returns 0: 1
# solution(2) returns 1: 2 -> 1
# solution(3) returns 2: 3 -> 2 -> 1
# solution(4) returns 2: 4 -> 2 -> 1
# solution(5) returns 3: 5 -> 4 -> 2 -> 1
# solution(6) returns 3: 6 -> 3 -> 2 -> 1
# solution(7) returns 4: 7 -> 6 -> 3 -> 2 -> 1
# solution(7) returns 4: 7 -> 8 -> 4 -> 2 -> 1
# solution(8) returns 3: 8 -> 4 -> 2 -> 1
# solution(9) returns 4: 9 -> 8 -> 4 -> 2 -> 1
# solution(9) returns 5: 9 -> 10 -> 5 -> 4 -> 2 -> 1
# solution(9) returns 6: 9 -> 10 -> 5 -> 6 -> 3 -> 2 -> 1
# solution(10) returns 4: 10 -> 5 -> 4 -> 2 -> 1
# solution(10) returns 5: 10 -> 5 -> 6 -> 3 -> 2 -> 1
# solution(10) returns 5: 10 -> 9 -> 8 -> 4 -> 2 -> 1
# solution(11) returns 5: 11 -> 12 -> 6 -> 3 -> 2 -> 1
# solution(11) returns 5: 11 -> 10 -> 5 -> 4 -> 2 -> 1
# solution(12) returns 4: 12 -> 6 -> 3 -> 2 -> 1
# solution(13) returns 5: 13 -> 12 -> 6 -> 3 -> 2 -> 1
# solution(13) returns 6: 13 -> 14 -> 7 -> 6 -> 3 -> 2 -> 1
# solution(13) returns 6: 13 -> 14 -> 7 -> 8 -> 4 -> 2 -> 1
# solution(14) returns 5: 14 -> 7 -> 8 -> 4 -> 2 -> 1
# solution(14) returns 5: 14 -> 7 -> 6 -> 3 -> 2 -> 1
# solution(15) returns 5: 15 -> 16 -> 8 -> 4 -> 2 -> 1
# solution(15) returns 6: 15 -> 14 -> 7 -> 6 -> 3 -> 2 -> 1
# solution(16) returns 4: 16 -> 8 -> 4 -> 2 -> 1
# solution(17) returns 5: 17 -> 16 -> 8 -> 4 -> 2 -> 1
# solution(17) returns 6: 17 -> 18 -> 9 -> 5 -> 4 -> 2 -> 1
# solution(17) returns 7: 17 -> 18 -> 9 -> 5 -> 6 -> 3 -> 2 -> 1
# solution(18) returns 5: 18 -> 9 -> 8 -> 4 -> 2 -> 1
# solution(18) returns 6: 18 -> 17 -> 16 -> 8 -> 4 -> 2 -> 1
# solution(19) returns 6: 19 -> 18 -> 9 -> 8 -> 4 -> 2 -> 1
# solution(1) returns 0: 1 .
# solution(2) returns 1: 2 -> 1 / #
# solution(3) returns 2: 3 -> 2 -> 1 - /
# solution(4) returns 2: 4 -> 2 -> 1 / / ###
# solution(5) returns 3: 5 -> 4 -> 2 -> 1 - / /
# solution(6) returns 3: 6 -> 3 -> 2 -> 1 / - /
# solution(7) returns 4: 7 -> 6 -> 3 -> 2 -> 1 - / - /
# solution(7) returns 4: 7 -> 8 -> 4 -> 2 -> 1 + / / / -
# solution(8) returns 3: 8 -> 4 -> 2 -> 1 / / / ###
# solution(9) returns 4: 9 -> 8 -> 4 -> 2 -> 1 - / / /
# solution(10) returns 4: 10 -> 5 -> 4 -> 2 -> 1 / - / /
# solution(11) returns 5: 11 -> 10 -> 5 -> 4 -> 2 -> 1 - / - / /
# solution(12) returns 4: 12 -> 6 -> 3 -> 2 -> 1 / / - /
# solution(13) returns 5: 13 -> 12 -> 6 -> 3 -> 2 -> 1 - / / - /
# solution(14) returns 5: 14 -> 7 -> 6 -> 3 -> 2 -> 1 / - / - / -
# solution(15) returns 5: 15 -> 16 -> 8 -> 4 -> 2 -> 1 + / / / / #
# solution(16) returns 4: 16 -> 8 -> 4 -> 2 -> 1 / / / / ###
# solution(17) returns 5: 17 -> 16 -> 8 -> 4 -> 2 -> 1 - / / / /
# solution(18) returns 5: 18 -> 9 -> 8 -> 4 -> 2 -> 1 / - / / /
# solution(19) returns 6: 19 -> 18 -> 9 -> 8 -> 4 -> 2 -> 1 - / - / / /
# solution(20) returns 5: 20 -> 10 -> 5 -> 4 -> 2 -> 1 / / - / /
# solution(21) returns 6: 21 -> 20 -> 10 -> 5 -> 4 -> 2 -> 1 - / / - / /
# solution(21) returns 6: 22 -> 11 -> 10 -> 5 -> 4 -> 2 -> 1 - / / - / /
# solution(30) returns _: 30 -> 15 -> 14 -> 7 -> 6 -> 3 -> 2 -> 1
# solution(30) returns _: 30 -> 31 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1 -
# solution(31) returns _: 31 -> 32 -> 15 -> 8 -> 4 -> 2 -> 1 #
# solution(32) returns 5: 32 -> 16 -> 8 -> 4 -> 2 -> 1 / / / / / ###
# solution(61) returns _: 61 -> 60 -> 30 -> 15 -> 14 -> 7 -> 6 -> 3 -> 2 -
# solution(62) returns 8: 62 -> 63 -> 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1 #
# solution(63) returns 7: 63 -> 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1 #
# solution(64) returns 6: 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1/ / / / / / ###
#
# solution(125) returns 11: 125 -> 124 -> 62 -> 31 -> 30 -> 15 -> 14 -> 7 -> 6 -> 3 -> 2 -> 1
# solution(125) returns 10: 125 -> 124 -> 62 -> 63 -> 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1
# solution(125) returns 10: 125 -> 126 -> 127 -> 128 -> 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1 -
# solution(126) returns 9: #
# solution(127) returns 8: #
# solution(128) returns 7: ###

View File

@ -0,0 +1,53 @@
# Step 1. if even, divide by two
# Step 2. if odd, add one and test if power of two - if true include as op
# Step 3. if odd, remove one
# test for 1 return op counter if true, else repeat
# solution(1) returns 0: 1 .
# solution(2) returns 1: 2 -> 1 / #
# solution(3) returns 2: 3 -> 2 -> 1 - /
# solution(4) returns 2: 4 -> 2 -> 1 / / ###
# solution(5) returns 3: 5 -> 4 -> 2 -> 1 - / /
# solution(6) returns 3: 6 -> 3 -> 2 -> 1 / - /
# solution(7) returns 4: 7 -> 6 -> 3 -> 2 -> 1 - / - /
# solution(7) returns 4: 7 -> 8 -> 4 -> 2 -> 1 + / / / -
# solution(8) returns 3: 8 -> 4 -> 2 -> 1 / / / ###
# solution(9) returns 4: 9 -> 8 -> 4 -> 2 -> 1 - / / /
# solution(10) returns 4: 10 -> 5 -> 4 -> 2 -> 1 / - / /
# solution(11) returns 5: 11 -> 10 -> 5 -> 4 -> 2 -> 1 - / - / /
# solution(12) returns 4: 12 -> 6 -> 3 -> 2 -> 1 / / - /
# solution(13) returns 5: 13 -> 12 -> 6 -> 3 -> 2 -> 1 - / / - /
# solution(14) returns 5: 14 -> 7 -> 6 -> 3 -> 2 -> 1 / - / - / -
# solution(15) returns 5: 15 -> 16 -> 8 -> 4 -> 2 -> 1 + / / / / #
# solution(16) returns 4: 16 -> 8 -> 4 -> 2 -> 1 / / / / ###
# solution(17) returns 5: 17 -> 16 -> 8 -> 4 -> 2 -> 1 - / / / /
# solution(18) returns 5: 18 -> 9 -> 8 -> 4 -> 2 -> 1 / - / / /
# solution(19) returns 6: 19 -> 18 -> 9 -> 8 -> 4 -> 2 -> 1 - / - / / /
# solution(20) returns 5: 20 -> 10 -> 5 -> 4 -> 2 -> 1 / / - / /
# solution(21) returns 6: 21 -> 20 -> 10 -> 5 -> 4 -> 2 -> 1 - / / - / /
# solution(21) returns 6: 22 -> 11 -> 10 -> 5 -> 4 -> 2 -> 1 - / / - / /
# solution(30) returns _: 30 -> 15 -> 14 -> 7 -> 6 -> 3 -> 2 -> 1
# solution(30) returns _: 30 -> 31 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1 -
# solution(31) returns _: 31 -> 32 -> 15 -> 8 -> 4 -> 2 -> 1 #
# solution(32) returns 5: 32 -> 16 -> 8 -> 4 -> 2 -> 1 / / / / / ###
# solution(61) returns _: 61 -> 60 -> 30 -> 15 -> 14 -> 7 -> 6 -> 3 -> 2 -
# solution(62) returns 8: 62 -> 63 -> 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1 #
# solution(63) returns 7: 63 -> 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1 #
# solution(64) returns 6: 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1/ / / / / / ###
#
# solution(125) returns 11: 125 -> 124 -> 62 -> 31 -> 30 -> 15 -> 14 -> 7 -> 6 -> 3 -> 2 -> 1
# solution(125) returns 10: 125 -> 124 -> 62 -> 63 -> 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1
# solution(125) returns 10: 125 -> 126 -> 127 -> 128 -> 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1 -
# solution(125) returns 9 : 125 -> 124 -> 62 -> 31 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1
# solution(126) returns 9: 126 -> 127 -> 128 -> 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1 #
# solution(126) returns 9: 126 -> 63 -> 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1
# solution(127) returns 8: 127 -> 128 -> 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1 #
# solution(128) returns 7: 128 -> 64 -> 32 -> 16 -> 8 -> 4 -> 2 -> 1 ###

View File

@ -0,0 +1,53 @@
Fuel Injection Perfection
=========================
Commander Lambda has asked for your help to refine the automatic quantum antimatter fuel injection system for her LAMBCHOP doomsday device. It's a great chance for you to get a closer look at the LAMBCHOP - and maybe sneak in a bit of sabotage while you're at it - so you took the job gladly.
Quantum antimatter fuel comes in small pellets, which is convenient since the many moving parts of the LAMBCHOP each need to be fed fuel one pellet at a time. However, minions dump pellets in bulk into the fuel intake. You need to figure out the most efficient way to sort and shift the pellets down to a single pellet at a time.
The fuel control mechanisms have three operations:
1) Add one fuel pellet
2) Remove one fuel pellet
3) Divide the entire group of fuel pellets by 2 (due to the destructive energy released when a quantum antimatter pellet is cut in half, the safety controls will only allow this to happen if there is an even number of pellets)
Write a function called solution(n) which takes a positive integer as a string and returns the minimum number of operations needed to transform the number of pellets to 1. The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits.
For example:
solution(4) returns 2: 4 -> 2 -> 1
solution(15) returns 5: 15 -> 16 -> 8 -> 4 -> 2 -> 1
Languages
=========
To provide a Python solution, edit solution.py
To provide a Java solution, edit Solution.java
Test cases
==========
Your code should pass the following test cases.
Note that it may also be run against hidden test cases not shown here.
-- Python cases --
Input:
solution.solution('15')
Output:
5
Input:
solution.solution('4')
Output:
2
-- Java cases --
Input:
Solution.solution('4')
Output:
2
Input:
Solution.solution('15')
Output:
5
Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder.

View File

@ -0,0 +1,16 @@
# i = 20
# while i > 0:
# print i
# if ((i >> 1) & 1) == 1:
# print "true: " + str(bin(i))
# else:
# print "false: " + str(bin(i))
# i = i - 1
print str(170) + " " + str(bin(170))
print str(170+1) + " " + str(bin(170+1))
print str(170+2) + " " + str(bin(170+2))
print str(170+3) + " " + str(bin(170+3))
print str(170+4) + " " + str(bin(170+4))
print str(170-1) + " " + str(bin(170-1))

View File

@ -0,0 +1,62 @@
def solution(n):
opCounter = 0
pellets = int(n)
while pellets > 1:
if pellets > 100:
print "Iteration Started w/ " + str(pellets) + " pellets left. - " + str(bin(pellets))
elif pellets < 100 and pellets > 9:
print "Iteration Started w/ " + str(pellets) + " pellets left. - " + str(bin(pellets))
else:
print "Iteration Started w/ " + str(pellets) + " pellets left. - " + str(bin(pellets))
if pellets % 2 == 0:
pellets /= 2
elif (pellets > 3 and (pellets & 1) == 1 and (pellets >> 1) & 1) == 1:
pellets += 1
else:
pellets -= 1
opCounter += 1
return opCounter
case1 = int(solution('372'))
if case1 == 11:
print "Test 1: Passed"
else:
print "Test 1: Failed"
print "Recieved " + str(case1)
case2 = int(solution('15'))
if case2 == 5:
print "Test 2: Passed"
else:
print "Test 2: Failed"
print "Recieved " + str(case2)
case3 = int(solution('5'))
if case3 == 3:
print "Test 3: Passed"
else:
print "Test 3: Failed"
print "Recieved " + str(case3)
case4 = int(solution('4'))
if case4 == 2:
print "Test 4: Passed"
else:
print "Test 4: Failed"
print "Recieved " + str(case4)
case5 = int(solution('170'))
if case5 == 10:
print "Test 5: Passed"
else:
print "Test 5: Failed"
print "Recieved " + str(case5)

View File

@ -0,0 +1,99 @@
class Fraction:
def __init__(self, num, den):
if num < 1 and num > 0:
self.num = num*100
self.den = 100
else:
self.num = num
self.den = den
self._simplify()
def __str__(self):
return str(self.num) + "/" + str(self.den)
def __radd__(self, other):
return self.__add__(other)
def __rsub__(self, other):
return self.__sub__(other)
def __rmul__(self, other):
return self.__mul__(other)
def __rdiv__(self, other):
return self.__div__(other)
def __add__(self, other):
if isinstance(other, self.__class__):
if self.den == other.den:
return Fraction(self.num + other.num, self.den)
else:
num = self.num * other.den + other.num * self.den
den = self.den * other.den
return Fraction(num, den)
elif isinstance(other, int):
return Fraction(self.num + (other * self.den), self.den)
def __sub__(self, other):
if isinstance(other, self.__class__):
if self.den == other.den:
return Fraction(self.num - other.num, self.den)
else:
return Fraction(((self.num * other.den)-(other.num*self.den)),self.den * other.den )
elif isinstance(other, int):
if other == 0:
return Fraction(-self.num, self.den)
else:
return Fraction(self.num - (other * self.den), self.den)
def __mul__(self, other):
if isinstance(other, self.__class__):
num = self.num * other.num
den = self.den * other.den
return Fraction(num, den)
elif isinstance(other, int):
return self * Fraction(other, 1)
def __div__(self, other):
if isinstance(other, self.__class__):
num = self.num * other.den
den = self.den * other.num
return Fraction(num, den)
elif isinstance(other, int):
return self / Fraction(other, 1)
def getNum(self):
return self.num
def getDen(self):
return self.den
def _gcf(self, first, second):
while second:
first, second = second, first % second
return first
def _simplify(self):
if self.den == 0:
return
gcf = self._gcf(self.num, self.den)
self.num = self.num / gcf
self.den = self.den / gcf
print Fraction(1, 3) + Fraction(1, 6)
print Fraction(1, 3) - Fraction(1, 6)
print Fraction(1, 3) * Fraction(1, 6)
print Fraction(1, 3) / Fraction(1, 6)
print Fraction(1,3) + 2
print Fraction(1,3) - 2
print Fraction(1,3) * 2
print Fraction(1,3) / 2
print 2 + Fraction(1,3)
print 2 - Fraction(1,3)
print 2 * Fraction(1,3)
print 2 / Fraction(1,3)
print Fraction(3, 12)

View File

@ -0,0 +1,199 @@
class Matrix:
def __init__(self, m):
self.matrix = [[0 for i in range(len(m[0]))] for j in range(len(m))]
for i, row in enumerate(m):
for j, col in enumerate(row):
self.matrix[i][j] = m[i][j]
self.I = []
self.R = []
self.Q = []
def __str__(self):
textArr = ""
for row in self.matrix:
for col in row:
if type(col) == int:
textArr += " " + str(col) + " "
else:
textArr += str(col) + " "
textArr += "\n"
return textArr
def __len__(self):
return len(self.matrix)
def __getitem__(self, i):
return self.matrix[i]
def __radd__(self, other):
return self.__add__(other)
def __rsub__(self, other):
return self.__sub__(other)
def __rmul__(self, other):
return self.__mul__(other)
def __add__(self, other):
result = [[0 for i in range(len(other.matrix[0]))] for j in range(len(other.matrix[0]))]
if isinstance(other, self.__class__):
for i in range(len(self.matrix)):
for j in range(len(other.matrix[0])):
result[i][j] = other.matrix[i][j] + other.matrix[i][j]
elif isinstance(other, int):
return "TODO: Matrix Add Function w/ Int"
return result
def __sub__(self, other):
if isinstance(other, self.__class__):
if len(self.matrix) < len(other.matrix):
short = self
else:
short = other
result = [[0 for i in range(len(short.matrix[0]))] for j in range(len(short.matrix[0]))]
for i in range(len(short.matrix)):
for j in range(len(short.matrix[0])):
result[i][j] = self.matrix[i][j] - other.matrix[i][j]
elif isinstance(other, int):
return "TODO: Matrix Sub Function w/ Int"
return result
def __mul__(self, other):
A = self
B = other
result = [[sum(a * b for a, b in zip(A_row, B_col))
for B_col in zip(*B)]
for A_row in A]
return result
def getI(self):
return self.I
def getR(self):
return self.R
def getQ(self):
return self.Q
def makeRegAndSTD(self):
m = self.matrix
shift = 0
# Point Terminal states to themselves and move to top of 2d array
for i, row in enumerate(m):
void = True
for col in row:
if col != 0:
void = False
if void == True:
row[i] = 1
m.insert(shift, row)
m.pop(i+1)
shift += 1
# Shift all elements relative to the nmber of terminal states found
for i, row in enumerate(m):
m[i] = m[i][-shift:] + m[i][:-shift]
# Extract sections of the matrix for use in calculating F
top = m[:shift]
bottom = m[shift:]
I = [[0 for i in range(len(m))] for j in range(shift)]
R = [[0 for i in range(len(m))] for j in range(len(m)-shift)]
Q = [[0 for i in range(len(m))] for j in range(len(m)-shift)]
for i, col in enumerate(top):
I[i] = col[:shift]
for i, col in enumerate(bottom):
R[i] = col[:shift]
Q[i] = col[shift:]
self.I = Matrix(I)
self.R = Matrix(R)
self.Q = Matrix(Q)
def transposeMatrix(m):
return map(list,zip(*m))
def getMatrixMinor(m,i,j):
return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])]
def getMatrixDeternminant(m):
#base case for 2x2 matrix
if len(m) == 2:
return m[0][0]*m[1][1]-m[0][1]*m[1][0]
determinant = 0
for c in range(len(m)):
determinant += ((-1)**c)*m[0][c]*getMatrixDeternminant(getMatrixMinor(m,0,c))
return determinant
def getMatrixInverse(m):
determinant = getMatrixDeternminant(m)
#special case for 2x2 matrix:
if len(m) == 2:
return [[m[1][1]/determinant, -1*m[0][1]/determinant],
[-1*m[1][0]/determinant, m[0][0]/determinant]]
#find matrix of cofactors
cofactors = []
for r in range(len(m)):
cofactorRow = []
for c in range(len(m)):
minor = getMatrixMinor(m,r,c)
cofactorRow.append(((-1)**(r+c)) * getMatrixDeternminant(minor))
cofactors.append(cofactorRow)
cofactors = transposeMatrix(cofactors)
for r in range(len(cofactors)):
for c in range(len(cofactors)):
cofactors[r][c] = cofactors[r][c]/determinant
return cofactors
def print2D(array):
for arr in array:
print arr
return ""
# ---------------------------------------------------------
m1 = Matrix([
[1,0],
[0,1]])
m2 = Matrix([
[.8, .1],
[.4, .4]])
m3 = Matrix([
[12, 7, 3],
[4, 5, 6],
[7, 8, 9]])
m4 = Matrix([
[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]
,[2, 3, 7,3]])
m5 = Matrix([
[0, 1, 0, 0, 0, 1],
[4, 0, 0, 3, 2, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
m6 = Matrix([
[.1,0,.8,.1],
[.1,.1,.4,.4],
[0,0,0,0],
[0,0,0,0],])
# ----------------------------------------------------------
print "Subtract"
print2D(m3 - m4)
print ""
print2D(m4 - m3)
# print "Subtract Whole Number"
# print2D(1 - m3)

View File

@ -0,0 +1,121 @@
def getInverse(self):
n = len(self.matrix)
AM = copy_matrix(self.getMatrix)
I = self.I
IM = copy_matrix(self.I)
indices = list(range(n))
for fd in range(n):
fdScaler = 1.0 / AM[fd][fd]
for j in range(n):
AM[fd][j] *= fdScaler
IM[fd][j] *= fdScaler
for i in indices[0:fd] + indices[fd+1:]:
crScaler = AM[i][fd]
for j in range(n):
AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
return IM
# -----------------------------------------------
def eliminate(r1, r2, col, target=0):
fac = (r2[col]-target) / r1[col]
for i in range(len(r2)):
r2[i] -= fac * r1[i]
def gauss(a):
for i in range(len(a)):
if a[i][i] == 0:
for j in range(i+1, len(a)):
if a[i][j] != 0:
a[i], a[j] = a[j], a[i]
break
else:
print("MATRIX NOT INVERTIBLE")
return -1
for j in range(i+1, len(a)):
eliminate(a[i], a[j], i)
for i in range(len(a)-1, -1, -1):
for j in range(i-1, -1, -1):
eliminate(a[i], a[j], i)
for i in range(len(a)):
eliminate(a[i], a[i], i, target=1)
return a
def inverse(a):
tmp = [[] for _ in a]
for i,row in enumerate(a):
assert len(row) == len(a)
tmp[i].extend(row + [0]*i + [1] + [0]*(len(a)-i-1))
gauss(tmp)
ret = []
for i in range(len(tmp)):
ret.append(tmp[i][len(tmp[i])//2:])
return ret
# -----------------------------------------------
def invert_matrix(AM, IM):
for fd in range(len(AM)):
fdScaler = 1.0 / AM[fd][fd]
for j in range(len(AM)):
AM[fd][j] *= fdScaler
IM[fd][j] *= fdScaler
for i in list(range(len(AM)))[0:fd] + list(range(len(AM)))[fd+1:]:
crScaler = AM[i][fd]
for j in range(len(AM)):
AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
return IM
def identity_matrix(n):
I = zeros_matrix(n, n)
for i in range(n):
I[i][i] = 1.0
return I
def copy_matrix(m):
print m
rows = len(m)
cols = len(m[0])
mc = []
while len(mc) < rows:
mc.append([])
while len(mc[-1]) < cols:
mc[-1].append(0.0)
for i in range(rows):
for j in range(rows):
mc[i][j] = m[i][j]
return mc
def zeros_matrix(rows, cols):
"""
Creates a matrix filled with zeros.
:param rows: the number of rows the matrix should have
:param cols: the number of columns the matrix should have
:returns: list of lists that form the matrix.
"""
M = []
while len(M) < rows:
M.append([])
while len(M[-1]) < cols:
M[-1].append(0.0)
return M
m = [
[1,.5],
[-0.44444,1]
]
def print2D(array):
for arr in array:
print arr
return ""
print2D(inverse(m))
print2D(invert_matrix(m, identity_matrix(2)))

View File

@ -0,0 +1,213 @@
from fractions import Fraction
import unittest
def mAdd(left, right):
if len(left[0]) < len(right[0]):
short = left
else:
short = right
result = [[0 for i in range(len(short))] for j in range(len(short[0]))]
for i in range(len(result)):
for j in range(len(result[0])):
result[i][j] = left[i][j] + right[i][j]
return result
def mSub(left, right):
if len(left[0]) < len(right[0]):
short = left
else:
short = right
result = [[0 for i in range(len(short))] for j in range(len(short[0]))]
for i in range(len(result)):
for j in range(len(result[0])):
result[i][j] = left[i][j] - right[i][j]
return result
def mMul(left, right):
result = [[sum(a * b for a, b in zip(left_row, right_col))
for right_col in zip(*right)]
for left_row in left]
return result
def makeIdentityM(s):
result = [[0 for i in range(s)] for j in range(s)]
for i, row in enumerate(result):
for j, col in enumerate(row):
if i == j:
result[i][j] = 1
return result
def makeRegAndSTD(m):
shift = 0
# Point Terminal states to themselves and move to top of 2d array
for i, row in enumerate(m):
void = True
for col in row:
if col != 0:
void = False
if void == True:
row[i] = 1
m.insert(shift, row)
m.pop(i+1)
shift += 1
# Shift all elements relative to the nmber of terminal states found
for i, row in enumerate(m):
m[i] = m[i][-shift:] + m[i][:-shift]
# Extract sections of the matrix for use in calculating F
top = m[:shift]
bottom = m[shift:]
I = [[0 for i in range(len(m))] for j in range(shift)]
R = [[0 for i in range(len(m))] for j in range(len(m)-shift)]
Q = [[0 for i in range(len(m))] for j in range(len(m)-shift)]
for i, col in enumerate(top):
I[i] = col[:shift]
for i, col in enumerate(bottom):
R[i] = col[:shift]
Q[i] = col[shift:]
return [m, I, R, Q]
def invertMatrix(AM, IM):
for fd in range(len(AM)):
fdScaler = 1.0 / AM[fd][fd]
for j in range(len(AM)):
AM[fd][j] *= fdScaler
IM[fd][j] *= fdScaler
for i in list(range(len(AM)))[0:fd] + list(range(len(AM)))[fd+1:]:
crScaler = AM[i][fd]
for j in range(len(AM)):
AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
return IM
def gcd(x, y):
while y:
x, y = y, x % y
return x
def transformProbabilities(m):
result = [0 for i in range(len(m))]
numerators = [0 for i in range(len(m))]
denomenators = [0 for i in range(len(m))]
for i, prob in enumerate(m):
x = Fraction(prob).limit_denominator(1000)
if str(x).find('/') != -1:
y = str(x).split('/')
numerators[i] = int(y[0])
denomenators[i] = int(y[1])
else:
numerators[i] = int(x)
lcm = denomenators[0]
# Protect by divide 0
if lcm == 0:
lcm = 1
for i in denomenators[1:]:
lcm = lcm*i/gcd(lcm, i)
# Make sure lcm is not 0
if lcm == 0:
lcm = 1
for i, num in enumerate(numerators):
if denomenators[i] != 0 and denomenators[i] != lcm:
result[i] = num * (lcm / denomenators[i])
else:
result[i] = num
result.append(lcm)
return result
def solution(m):
# Check if our matrix is 1 x 1
try:
m[0][1]
except IndexError:
return [1,1]
# Check if S0 is Terminal State
isTerminal = True
for item in m[0][1:]:
if item != 0:
isTerminal = False
if isTerminal == True:
result = [1]
for i, row in enumerate(m[1:]):
void = True
for col in row:
if col != 0:
void = False
if void == True:
result.append(0)
result.append(1)
return result
# Write fractions to matrix (for help with math)
for i, row in enumerate(m):
den = 0
for j, col in enumerate(row):
den += m[i][j]
for j, col in enumerate(row):
if m[i][j] != 0 and den != 0:
m[i][j] = Fraction(m[i][j], den)
# Returns [m, I, R, Q]
helpers = makeRegAndSTD(m)
iq = mSub(helpers[1], helpers[3])
F = invertMatrix(iq, makeIdentityM(len(iq)))
FR = mMul(F, helpers[2])
return transformProbabilities(FR[0])
class TestDoomsdayFuel(unittest.TestCase):
def test1(self):
test_input = [
[0, 2, 1, 0, 0],
[0, 0, 0, 3, 4],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
self.assertEqual(solution(test_input),
[7, 6, 8, 21])
def test2(self):
test_input = [
[0, 1, 0, 0, 0, 1],
[4, 0, 0, 3, 2, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]
]
self.assertEqual(solution(test_input), [0, 3, 2, 9, 14])
def test3(self):
test_input = [
[0, 1, 0, 0, 0, 1],
[1, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]
]
self.assertEqual(solution(test_input), [0, 1, 1, 3, 5])
def test4(self):
test_input = [
[1, 1, 0, 1],
[1, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
]
self.assertEqual(solution(test_input), [0, 1, 1])
def test5(self):
test_input = [
[0, 1, 0],
[1, 1, 1],
[0, 0, 0]
]
self.assertEqual(solution(test_input), [1, 0, 1])
unittest.main()

View File

@ -0,0 +1,65 @@
Doomsday Fuel
=============
Making fuel for the LAMBCHOP's reactor core is a tricky process because of the exotic matter involved. It starts as raw ore, then during processing, begins randomly changing between forms, eventually reaching a stable form. There may be multiple stable forms that a sample could ultimately reach, not all of which are useful as fuel.
Commander Lambda has tasked you to help the scientists increase fuel creation efficiency by predicting the end state of a given ore sample. You have carefully studied the different structures that the ore can take and which transitions it undergoes. It appears that, while random, the probability of each structure transforming is fixed. That is, each time the ore is in 1 state, it has the same probabilities of entering the next state (which might be the same state). You have recorded the observed transitions in a matrix. The others in the lab have hypothesized more exotic forms that the ore can become, but you haven't seen all of them.
Write a function solution(m) that takes an array of array of nonnegative ints representing how many times that state has gone to the next state and return an array of ints for each terminal state giving the exact probabilities of each terminal state, represented as the numerator for each state, then the denominator for all of them at the end and in simplest form. The matrix is at most 10 by 10. It is guaranteed that no matter which state the ore is in, there is a path from that state to a terminal state. That is, the processing will always eventually end in a stable state. The ore starts in state 0. The denominator will fit within a signed 32-bit integer during the calculation, as long as the fraction is simplified regularly.
For example, consider the matrix m:
[
[0,1,0,0,0,1], # s0, the initial state, goes to s1 and s5 with equal probability
[4,0,0,3,2,0], # s1 can become s0, s3, or s4, but with different probabilities
[0,0,0,0,0,0], # s2 is terminal, and unreachable (never observed in practice)
[0,0,0,0,0,0], # s3 is terminal
[0,0,0,0,0,0], # s4 is terminal
[0,0,0,0,0,0], # s5 is terminal
]
So, we can consider different paths to terminal states, such as:
s0 -> s1 -> s3
s0 -> s1 -> s0 -> s1 -> s0 -> s1 -> s4
s0 -> s1 -> s0 -> s5
Tracing the probabilities of each, we find that
s2 has probability 0
s3 has probability 3/14
s4 has probability 1/7
s5 has probability 9/14
So, putting that together, and making a common denominator, gives an answer in the form of
[s2.numerator, s3.numerator, s4.numerator, s5.numerator, denominator] which is
[0, 3, 2, 9, 14].
Languages
=========
To provide a Java solution, edit Solution.java
To provide a Python solution, edit solution.py
Test cases
==========
Your code should pass the following test cases.
Note that it may also be run against hidden test cases not shown here.
-- Java cases --
Input:
Solution.solution({{0, 2, 1, 0, 0}, {0, 0, 0, 3, 4}, {0, 0, 0, 0, 0}, {0, 0, 0, 0,0}, {0, 0, 0, 0, 0}})
Output:
[7, 6, 8, 21]
Input:
Solution.solution({{0, 1, 0, 0, 0, 1}, {4, 0, 0, 3, 2, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0}})
Output:
[0, 3, 2, 9, 14]
-- Python cases --
Input:
solution.solution([[0, 2, 1, 0, 0], [0, 0, 0, 3, 4], [0, 0, 0, 0, 0], [0, 0, 0, 0,0], [0, 0, 0, 0, 0]])
Output:
[7, 6, 8, 21]
Input:
solution.solution([[0, 1, 0, 0, 0, 1], [4, 0, 0, 3, 2, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]])
Output:
[0, 3, 2, 9, 14]
Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder.

View File

@ -0,0 +1,326 @@
class Fraction:
def __init__(self, num, den):
if num < 1 and num > 0:
self.num = num*100
self.den = 100
else:
self.num = num
self.den = den
self._simplify()
def __str__(self):
return str(self.num) + "/" + str(self.den)
def __radd__(self, other):
return self.__add__(other)
def __rsub__(self, other):
return self.__sub__(other)
def __rmul__(self, other):
return self.__mul__(other)
def __rdiv__(self, other):
return self.__div__(other)
def __add__(self, other):
if isinstance(other, self.__class__):
if self.den == other.den:
return Fraction(self.num + other.num, self.den)
else:
num = self.num * other.den + other.num * self.den
den = self.den * other.den
return Fraction(num, den)
elif isinstance(other, int):
return Fraction(self.num + (other * self.den), self.den)
def __sub__(self, other):
if isinstance(other, self.__class__):
if self.den == other.den:
return Fraction(self.num - other.num, self.den)
else:
return Fraction(((self.num * other.den)-(other.num*self.den)),self.den * other.den)
elif isinstance(other, int):
if other == 0:
return Fraction(-self.num, self.den)
else:
return Fraction(self.num - (other * self.den), self.den)
elif isinstance(other, float):
if other == 0:
return Fraction(-self.num, self.den)
else:
return Fraction(self.num - (other * self.den), self.den)
def __mul__(self, other):
if isinstance(other, self.__class__):
num = self.num * other.num
den = self.den * other.den
return Fraction(num, den)
elif isinstance(other, int):
return self * Fraction(other, 1)
elif isinstance(other, float):
return self * Fraction(other, 1)
def __div__(self, other):
if isinstance(other, self.__class__):
num = self.num * other.den
den = self.den * other.num
return Fraction(num, den)
elif isinstance(other, int):
return self / Fraction(other, 1)
def getNum(self):
return self.num
def getDen(self):
return self.den
def _gcf(self, first, second):
while second:
first, second = second, first % second
return first
def _simplify(self):
if self.den == 0:
return
gcf = self._gcf(self.num, self.den)
self.num = self.num / gcf
self.den = self.den / gcf
class Matrix:
def __init__(self, m):
self.matrix = [[0 for i in range(len(m[0]))] for j in range(len(m))]
for i, row in enumerate(m):
for j, col in enumerate(row):
self.matrix[i][j] = m[i][j]
self.I = []
self.R = []
self.Q = []
def __str__(self):
textArr = ""
for row in self.matrix:
for col in row:
if type(col) == int:
textArr += " " + str(col) + " "
else:
textArr += str(col) + " "
textArr += "\n"
return textArr
def __len__(self):
return len(self.matrix)
def __getitem__(self, i):
return self.matrix[i]
def __radd__(self, other):
return self.__add__(other)
def __rsub__(self, other):
return self.__sub__(other)
def __rmul__(self, other):
return self.__mul__(other)
def __add__(self, other):
result = [[0 for i in range(len(other.matrix[0]))] for j in range(len(other.matrix[0]))]
if isinstance(other, self.__class__):
for i in range(len(self.matrix)):
for j in range(len(other.matrix[0])):
result[i][j] = other.matrix[i][j] + other.matrix[i][j]
elif isinstance(other, int):
return "TODO: Matrix Add Function w/ Int"
return result
def __sub__(self, other):
if isinstance(other, self.__class__):
if len(self.matrix) < len(other.matrix):
short = self
else:
short = other
result = [[0 for i in range(len(short.matrix[0]))] for j in range(len(short.matrix[0]))]
for i in range(len(short.matrix)):
for j in range(len(short.matrix[0])):
result[i][j] = self.matrix[i][j] - other.matrix[i][j]
elif isinstance(other, int):
return "TODO: Matrix Sub Function w/ Int"
return result
def __mul__(self, other):
A = self
B = other
result = [[sum(a * b for a, b in zip(A_row, B_col))
for B_col in zip(*B)]
for A_row in A]
return result
def getMatrix(self):
return self.matrix
def getI(self):
return self.I
def getR(self):
return self.R
def getQ(self):
return self.Q
def makeRegAndSTD(self):
m = self.matrix
shift = 0
# Point Terminal states to themselves and move to top of 2d array
for i, row in enumerate(m):
void = True
for col in row:
if col != 0:
void = False
if void == True:
row[i] = 1
m.insert(shift, row)
m.pop(i+1)
shift += 1
# Shift all elements relative to the nmber of terminal states found
for i, row in enumerate(m):
m[i] = m[i][-shift:] + m[i][:-shift]
# Extract sections of the matrix for use in calculating F
top = m[:shift]
bottom = m[shift:]
I = [[0 for i in range(len(m))] for j in range(shift)]
R = [[0 for i in range(len(m))] for j in range(len(m)-shift)]
Q = [[0 for i in range(len(m))] for j in range(len(m)-shift)]
for i, col in enumerate(top):
I[i] = col[:shift]
for i, col in enumerate(bottom):
R[i] = col[:shift]
Q[i] = col[shift:]
self.I = Matrix(I)
self.R = Matrix(R)
self.Q = Matrix(Q)
def invertMatrix(AM, IM):
for fd in range(len(AM)):
fdScaler = 1.0 / AM[fd][fd]
for j in range(len(AM)):
AM[fd][j] *= fdScaler
IM[fd][j] *= fdScaler
for i in list(range(len(AM)))[0:fd] + list(range(len(AM)))[fd+1:]:
crScaler = AM[i][fd]
for j in range(len(AM)):
AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
return IM
def fetchProbabilities(m):
nums = [0]*len(m[0])
dens = [0]*len(m[0])
results = [0]*len(m[0])
for i, col in enumerate(m[0]):
nums[i] = col.getNum()
dens[i] = col.getDen()
# RISK: both denominators might need to get changed (not just go into the biggest)
commonDen = dens[0]
for col in dens[1:]:
if col > commonDen:
commonDen = col
for i, col in enumerate(nums):
if dens[i] != commonDen:
results[i] = nums[i] * (commonDen / dens[i])
results.append(commonDen)
return results
def solution(m):
# Change probabilities to Fractions' for easy working
for i, row in enumerate(m):
den = 0
for j, col in enumerate(row):
den += m[i][j]
for j, col in enumerate(row):
if m[i][j] != 0 and den != 0:
m[i][j] = Fraction(m[i][j], den)
m = Matrix(m)
print "Input: \n" + m.__str__()
m.makeRegAndSTD()
print "STD: \n" + m.__str__()
iq = Matrix(m.getI() - m.getQ())
print "I-Q: \n" + iq.__str__()
F = invertMatrix(iq.getMatrix(), [[1,0],[0,1]])
print "F: \n" + F.__str__()
FR = Matrix(F * m.getR())
print "FR: \n" + FR.__str__()
return fetchProbabilities(FR)
# set1 = [
# [0, 2, 1, 0, 0],
# [0, 0, 0, 3, 4],
# [0, 0, 0, 0, 0],
# [0, 0, 0, 0,0],
# [0, 0, 0, 0, 0]
# ]
# set1Out = [7, 6, 8, 21]
set2 = [
[0, 1, 0, 0, 0, 1],
[4, 0, 0, 3, 2, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]
]
set2Out = [0, 3, 2, 9, 14]
# set3 = [
# [1,0,0,0],
# [0,1,0,0],
# [0,0,1,0],
# [0,0,0,1]
# ]
# set3Out = [1, 1]
# case1 = solution(set1)
# if case1 == set1Out:
# print "Test 1: Passed"
# else:
# print "Test 1: Failed"
# print "Recieved " + str(case1)
case2 = solution(set2)
if case2 == set2Out:
print "Test 2: Passed"
else:
print "Test 2: Failed"
print "Recieved " + str(case2)
# case3 = solution(set3)
# if case3 == set3Out:
# print "Test 3: Passed"
# else:
# print "Test 3: Failed"
# print "Recieved " + str(case3)
def print2D(array):
for arr in array:
print arr
return ""

View File

@ -0,0 +1,206 @@
from fractions import Fraction
def mAdd(left, right):
if len(left[0]) < len(right[0]):
short = left
else:
short = right
result = [[0 for i in range(len(short))] for j in range(len(short[0]))]
for i in range(len(result)):
for j in range(len(result[0])):
result[i][j] = left[i][j] + right[i][j]
return result
def mSub(left, right):
if len(left[0]) < len(right[0]):
short = left
else:
short = right
result = [[0 for i in range(len(short))] for j in range(len(short[0]))]
for i in range(len(result)):
for j in range(len(result[0])):
result[i][j] = left[i][j] - right[i][j]
return result
def mMul(left, right):
result = [[sum(a * b for a, b in zip(left_row, right_col))
for right_col in zip(*right)]
for left_row in left]
return result
def makeIdentityM(s):
result = [[0 for i in range(s)] for j in range(s)]
for i, row in enumerate(result):
for j, col in enumerate(row):
if i == j:
result[i][j] = 1
return result
def makeRegAndSTD(m):
shiftU = 0
# Point Terminal states to themselves and move to top of 2d array
for i, row in enumerate(m):
void = True
for col in row:
if col != 0:
void = False
if void == True:
m[i][i] = 1
m.insert(shiftU, row)
m.pop(i+1)
shiftU += 1
print "Void -----"
print2D(m)
# Shift all elements relative to the nmber of terminal states found
shiftR = shiftU
if len(m[0]) % 2 != 0:
shiftR = shiftU + 1
print "ShiftR: " + str(shiftR)
for i, row in enumerate(m):
print "Shift -----"
print2D(m)
m[i] = m[i][-shiftR:] + m[i][:-shiftR]
# Extract sections of the matrix for use in calculating F
top = m[:shiftU]
bottom = m[shiftU:]
I = [[0 for i in range(len(top))] for j in range(len(top[0])-shiftR)]
for i, row in enumerate(I):
for j, col in enumerate(row):
I[i][j] = m[i][j]
print "NEW I"
print2D(I)
R = [[0 for i in range(ShiftU)] for j in range(len(m)-shiftR)]
Q = [[0 for i in range(ShiftU)] for j in range(len(shiftU)-shiftR)]
for i, col in enumerate(bottom):
R[i] = col[:shiftR]
Q[i] = col[shiftR:]
return [m, I, R, Q]
def invertMatrix(AM, IM):
for fd in range(len(AM)):
fdScaler = 1.0 / AM[fd][fd]
for j in range(len(AM)):
AM[fd][j] *= fdScaler
IM[fd][j] *= fdScaler
for i in list(range(len(AM)))[0:fd] + list(range(len(AM)))[fd+1:]:
crScaler = AM[i][fd]
for j in range(len(AM)):
AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
return IM
def gcd(x, y):
while y:
x, y = y, x % y
return x
def transformProbabilities(m):
result = [0 for i in range(len(m))]
numerators = [0 for i in range(len(m))]
denomenators = [0 for i in range(len(m))]
for i, prob in enumerate(m):
x = Fraction(prob).limit_denominator(1000)
if str(x).find('/') != -1:
y = str(x).split('/')
numerators[i] = int(y[0])
denomenators[i] = int(y[1])
else:
numerators[i] = int(x)
lcm = denomenators[0]
# Protect by divide 0
if lcm == 0:
lcm = 1
for i in denomenators[1:]:
lcm = lcm*i/gcd(lcm, i)
# Make sure lcm is not 0
if lcm == 0:
lcm = 1
for i, num in enumerate(numerators):
if denomenators[i] != 0 and denomenators[i] != lcm:
result[i] = num * (lcm / denomenators[i])
else:
result[i] = num
result.append(lcm)
return result
def solution(m):
# Check if our matrix is 1 x 1
try:
m[0][1]
except IndexError:
return [1,1]
# Check if S0 is Terminal State
isTerminal = True
for item in m[0][1:]:
if item != 0:
isTerminal = False
if isTerminal == True:
result = [1]
for i, row in enumerate(m[1:]):
void = True
for col in row:
if col != 0:
void = False
if void == True:
result.append(0)
result.append(1)
return result
# Write fractions to matrix (for help with math)
# for i, row in enumerate(m):
# den = 0
# for j, col in enumerate(row):
# den += m[i][j]
# for j, col in enumerate(row):
# if m[i][j] != 0 and den != 0:
# m[i][j] = Fraction(m[i][j], den)
# Returns [m, I, R, Q]
helpers = makeRegAndSTD(m)
iq = mSub(helpers[1], helpers[3])
print "m"
print2D(helpers[0])
print "I"
print2D(helpers[1])
print "R"
print2D(helpers[2])
print "Q"
print2D(helpers[3])
print2D(iq)
F = invertMatrix(iq, makeIdentityM(len(iq)))
FR = mMul(F, helpers[2])
return transformProbabilities(FR[0])
def print2D(array):
for arr in array:
print arr
return ""
test_input = [
[0, 0, 1],
[0, 0, 0],
[1, 1, 1]
]
print2D(test_input)
print solution(test_input)
# test_input = [
# [0,1,0],
# [0,1,0],
# [0,0,1]
# ]
# print2D(test_input)
# print solution(test_input)

7
README.md Normal file
View File

@ -0,0 +1,7 @@
# Overview
Google Foobar was a secret recruiting program by Google designed to hire developers based on their coding skills. The program was invite-only and usually based off your search history. There were also puzzles that you could solve to get an invite.
It looks like the program has been discontinued as of April 1st, 2024 according to foobar.withgoogle.com text description in search results.
Back in 2020 I solved a puzzle and got access to Google Foobar. I learned Python while I went through the challenge. This was also a great exposure to bitwise operators and markov chains.