diff --git a/solutions/esab-atad/README.md b/solutions/esab-atad/README.md new file mode 100644 index 00000000..fd0cac5e --- /dev/null +++ b/solutions/esab-atad/README.md @@ -0,0 +1,16 @@ +# ESAb ATAd + +Last year, a research consortium had some trouble with a distributed database system that sometimes lost pieces of the data. You do not need to read or understand that problem in order to solve this one! + +The consortium has decided that distributed systems are too complicated, so they are storing B bits of important information in a single array on one awesome machine. As an additional layer of security, they have made it difficult to obtain the information quickly; the user must query for a bit position between 1 and B, and then they receive that bit of the stored array as a response. + +Unfortunately, this ultra-modern machine is subject to random quantum fluctuations! Specifically, after every 1st, 11th, 21st, 31st... etc. query is sent, but before the response is given, quantum fluctuation causes exactly one of the following four effects, with equal probability: + +- 25% of the time, the array is complemented: every 0 becomes a 1, and vice versa. +- 25% of the time, the array is reversed: the first bit swaps with the last bit, the second bit swaps with the second-to-last bit, and so on. +- 25% of the time, both of the things above (complementation and reversal) happen to the array. (Notice that the order in which they happen does not matter.) +- 25% of the time, nothing happens to the array. + +Moreover, there is no indication of what effect the quantum fluctuation has had each time. The consortium is now concerned, and it has hired you to get its precious data back, in whatever form it is in! Can you find the entire array, such that your answer is accurate as of the time that you give it? Answering does not count as a query, so if you answer after your 30th query, for example, the array will be the same as it was after your 21st through 30th queries. + +More details: https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd27/0000000000209a9e diff --git a/solutions/esab-atad/go/esab-atad.go b/solutions/esab-atad/go/esab-atad.go new file mode 100644 index 00000000..4e12812b --- /dev/null +++ b/solutions/esab-atad/go/esab-atad.go @@ -0,0 +1,98 @@ +package main + +import ( + "bufio" + . "fmt" // Like C++ with the namespace, you use the functions without the 'fmt.' part + . "os" +) + +var B, T int //where B is the size of the test, and T the number of Test Sets + +var rd *bufio.Reader = bufio.NewReader(Stdin) +var wr *bufio.Writer = bufio.NewWriter(Stdout) + +func main() { + Scanf("%d%d", &T, &B) + //Iterate trought all the cases + for i := 1; i <= T; i++ { + var DB = make([]int, B+1) + var L int = 1 + var R int = B + for Q := 1; true; Q += 2 { //To keep an eye to the query number + if Q%10 == 1 && Q != 1 { + p := -1 + asim := -1 + for i := 1; i < L; i++ { + if DB[i] == DB[B+1-i] { + p = i + } else { + asim = i + } + } + if p == -1 { + status := query(1) + query(1) + if status != DB[1] { + for i := 1; i <= L; i++ { + DB[i] ^= 1 + } + for i := R; i <= B; i++ { + DB[i] ^= 1 + } + } + } else { + status := query(p) + if status != DB[p] { + for i := 1; i <= L; i++ { + DB[i] ^= 1 + } + for i := R; i <= B; i++ { + DB[i] ^= 1 + } + } + if asim == -1 { + query(p) + } else { + if query(asim) != DB[asim] { + for i, j := 1, len(DB)-1; i < j; i, j = i+1, j-1 { + DB[i], DB[j] = DB[j], DB[i] + } + } + } + } + Q += 2 + } + DB[L] = query(L) + DB[R] = query(R) + L += 1 + R -= 1 + if L > R { //Means that we already have all the database + for i := 1; i <= B; i++ { + Printf("%d", DB[i]) + } + Println() + var res string + Scanf("%s", &res) + if res == "N" { //Exit in case that our response is incorrect + Exit(0) + } else { + break + } + + } + } + } +} + +// To ask for a bit inside the database +func query(pos int) int { + Printf("%d\n", pos) + defer wr.Flush() + var bit int + Scanf("%d", &bit) + return bit +} + +//Let me out of go jaj +//Note: Go is a good language, the thing was that +//I just used to much python. diff --git a/solutions/esab-atad/java/esab-atad.java b/solutions/esab-atad/java/esab-atad.java new file mode 100644 index 00000000..5876e84d --- /dev/null +++ b/solutions/esab-atad/java/esab-atad.java @@ -0,0 +1,112 @@ +import java.util.Scanner; + +class Solution { + + public static Scanner sc= new Scanner(System.in); + public static int count = 0; + + public static void fillArray(int arr[]){ + int size = arr.length; + for (int i = 0; i < size; i++){ + arr[i] = 0; + } + } + + public static void printArray(int arr[]){ + int size = arr.length; + for (int i = 0; i < size; i++){ + System.out.print(arr[i]); + } + System.out.print("\n"); + } + + public static void complement(int arr[]){ + int size = arr.length; + for (int i = 0; i < size; i++){ + arr[i] ^= 1; + } + } + + public static void reverse(int arr[]){ + int size = arr.length; + int tmp = 0; + for (int i = 0; i < Math.floor(size/2); i++){ + tmp = arr[i]; + arr[i] = arr[size-1-i]; + arr[size-1-i] = tmp; + } + } + + public static int query(int i){ + + if(i != -1){ + System.out.print(i+1); + } + else{ + System.out.print("1"); + } + System.out.print("\n"); + count++; + int input = sc.nextInt(); + sc.nextLine(); + return input; + } + + public static void checkCorrect(int arr[]){ + printArray(arr); + String input = sc.nextLine(); + + if (!input.equals("Y")) + System.exit(0); + + } + + public static void esab_atad(int B){ + int result[] = new int[B]; + int complement_i = -1; + int reverse_i = -1; + int complement_res = 0; + int reverse_res = 0; + count = 0; + fillArray(result); + for (int i = 0; i < Math.floor(B / 2); i++){ + if(count != 0 && count%10 == 0){ + complement_res = query(complement_i); + reverse_res = query(reverse_i); + + if ( complement_i != -1 && (result[complement_i]^complement_res) == 1) + complement(result); + + if ( reverse_i != -1 && (result[reverse_i]^reverse_res) == 1 + ) + reverse(result); + } + + result[i] = query(i); + + result[B-i-1] = query(B-i-1); + + if( result[i] == result[B-i-1]) + complement_i = i; + else + reverse_i = i; + } + checkCorrect(result); + } + + public static void main(String[] args) { + int T; + int B; + String input; + String[] inputSplit; + input = sc.nextLine(); + inputSplit = input.split(" "); + + T = Integer.parseInt(inputSplit[0]); + B = Integer.parseInt(inputSplit[1]); + + for (int i = 0; i < T; i++){ + esab_atad(B); + } + } +} diff --git a/solutions/esab-atad/lisp/esab-atad.lisp b/solutions/esab-atad/lisp/esab-atad.lisp new file mode 100644 index 00000000..4ed29842 --- /dev/null +++ b/solutions/esab-atad/lisp/esab-atad.lisp @@ -0,0 +1,145 @@ +;; Function that gets a bit from the judge +(defun get-bit (idx) + (if (not idx) + (progn (format t "~d~%" 1) ;; In case idx is nil + (finish-output) + (parse-integer (read-line)) + nil) + (progn (format t "~d~%" (1+ idx)) ;; idx is a valid number + (finish-output) + (parse-integer (read-line))))) + +;; Function to query a pair of bits +(defun get-pair (left-idx) + (values (get-bit left-idx) (get-bit (- +number-length+ left-idx 1)))) ;; Return the left bit an its counterpart + +; Function that returns true if left and right are symmetric (equal) +(defun symmetricp (left right) + (= left right)) + +;; Function that checks if the digit has changed after fluctuation +(defun digit-changed (old-value new-value) + (/= old-value new-value)) + +;; Function that returns the type of fluctuation when we have both pairs +(defun get-fluctuation-sym-asym (old-sym-value old-asym-value new-sym-value new-asym-value) + (cond + ((and (/= old-sym-value new-sym-value) + (/= old-asym-value new-asym-value)) + ; Symmetrical AND asymmetrical changed + "C") + ((/= old-sym-value new-sym-value) ; Only symmetrical changed + "CR") + ((/= old-asym-value new-asym-value) ; Only asymmetrical changed + "R") + (t "N")) ; Neither changed + ) + +;; Function that returns the fluctuation type when we have only a symmetrical pair +(defun get-fluctuation-sym (old-sym-value new-sym-value) + (if (/= old-sym-value new-sym-value) + "C" + "N")) + +;; Function that returns the fluctuation type when we have only an asymmetrical pair +(defun get-fluctuation-asym (old-asym-value new-asym-value) + (if (/= old-asym-value new-asym-value) + "C" + "N")) + +;; Function that gets the fluctuation type, calls helper functions +(defun get-fluctuation-type (old-sym-value old-asym-value new-sym-value new-asym-value ) + (cond ( (and old-sym-value old-asym-value) ; We have both pairs stored + (get-fluctuation-sym-asym old-sym-value old-asym-value new-sym-value new-asym-value)) ; Call helper function + ; We only have one pair + ( old-sym-value ; We only have sym + (get-fluctuation-sym old-sym-value new-sym-value) ; Call helper function + ) + ; We only have asym + (t (get-fluctuation-asym old-asym-value new-asym-value)) ; Call helper function + ) +) + +;; Function that changes 0s to 1s and viceversa .VERIFICAR CUANDO ELEMENTO DE ARR ES NIL +(defun complement-array (arr) ; bit index) + (loop for i from 0 to (- +number-length+ 1) do ; Loop through the array + (if (eql (aref arr i) 0) ; If the current bit is a 0 + (setf (elt arr i) 1) ; Set the bit to a 1 + (setf (elt arr i) 0) ; Set the bit to a 0 +))) + +;; Function that updates our stored array +(defun update-array (arr bit-index fluct-type) + (cond ( (equal fluct-type "C") ; If the fluctuation type is a C + (complement-array arr ) ; We complement the array + ) + ( (equal fluct-type "R") ; If the fluctuation type is an R + (setf arr (nreverse arr)) ; We reverse the array + ) + ( (equal fluct-type "CR") ; If the fluctuation type is a CR + (complement-array arr) ; We complement the array + (setf arr (nreverse arr)) ; We also reverse the array + ) + (t nil) ; We leave our array the same + ) +) + +;; Helper function to convert an array to a list +(defun array-to-list (array) + (map 'list #'identity array)) + +;; Helper function that splits the input into ints +(defun split-space (s) + (let ( (space-idx (position #\Space s))) + ;Return inputs as ints + (values (parse-integer (subseq s 0 space-idx)) (parse-integer (subseq s (1+ space-idx))) ))) + +;; Function that solves a test case +(defun solve-test-case (length) + ;; Solve cases + (defconstant +number-length+ length) ; Define constant length of arrays + (defparameter arr (make-array +number-length+ :initial-element nil)) ; Create empty array of the length inputed + ; Declare symmetrical and asymmetrical indexes, number of queries and current index + (let ((sym-index nil) + (asym-index nil) + (queries 0) + (bit-index 0)) + (loop + (when (= bit-index (floor (/ +number-length+ 2))) (return)) ; Loop through the half of the array + (multiple-value-bind (left right) (get-pair bit-index) ; Declare left and right values + (setf queries (+ queries 2)) ; Add 2 to the queries + (if (or (not sym-index) (not asym-index)) ; If we dont have a sym or asym pair + (if (symmetricp left right) ; Check if its symmetrical + (if (not sym-index) (setf sym-index bit-index)) ; Set sym index, if we dont have one + (if (not asym-index) (setf asym-index bit-index)))) ; Set asym index, if we dont have one + + (if (and (= (mod queries 10) 2) (/= bit-index 0)) ; Check if a fluctuation happened + (progn + (let ((new-sym-value (get-bit sym-index)) ; Get fluctuation and update accordingly + (new-asym-value (get-bit asym-index)) + (old-sym-value (if (not sym-index) nil (elt arr sym-index))) + (old-asym-value (if (not asym-index) nil (elt arr asym-index)))) + (update-array arr + bit-index + (get-fluctuation-type old-sym-value + old-asym-value + new-sym-value + new-asym-value))) + (setf queries (+ queries 2))) ; Add 2 to the queries + ) + (setf (elt arr bit-index) left) ; Set new left value + (setf (elt arr (- +number-length+ bit-index 1)) right) ; Set new right value + (setf bit-index (1+ bit-index)) ; Add one to the current index + )) + (format t "~{~d~}~%" (array-to-list arr)))) ; Print array + +(defun main () + (setf in (read-line)) ; Read input + (multiple-value-bind (test-cases length) (split-space in) ; Format input into test-cases and length + (loop for test from 0 to (- test-cases 1) do ; Loop test-cases times + (solve-test-case length) + (setf result (read-line)) + (if (equal result "N") (return))) ; If we got a wrong answer, stop the program + )) + +(main) \ No newline at end of file diff --git a/solutions/esab-atad/python/esab-atad.py b/solutions/esab-atad/python/esab-atad.py new file mode 100644 index 00000000..88c41fcc --- /dev/null +++ b/solutions/esab-atad/python/esab-atad.py @@ -0,0 +1,130 @@ +"""ESAb ATAd + +This is a solution for the Google Code Jam 'ESAb ATAd' problem +Initially, this program reads a single line containing two integers T and B: +the number of test cases and the number of bits in the array, respectively + +The program then asks for each bit of information in the array +with queries to the stdout and readings via stdin + +More information: +https://codingcompetitions.withgoogle.com/ + codejam/round/000000000019fd27/0000000000209a9e +""" + +import sys + +def getBit(index): + print(index) + sys.stdout.flush() + return input() + +def getPair(data, left, b): + """Gets a symmetric pair of bits in the array + + Queries for a symmetric pair of bits and stores the values in data + it also stores if the pair has equal or different values + + Args: + data: list of dicts where local data is being stored + left: index of the left bit of the pair to query + b: length of the data array in the db system + """ + right = b - 1 - left + data[left]['val'] = getBit(left+1) # add 1 because db system indexes from 1 + data[right]['val'] = getBit(right+1) # add 1 because db system indexes from 1 + + # info about different or equal symmetric values are stored in 'sym' property + data[left]['sym'] = data[left]['val'] == data[right]['val'] + data[right]['sym'] = data[left]['sym'] + +def getFluctuationType(data): + # finds the index on the local data array of the first bit + # with a symmetric pair with equal value or None if does not exist such bit + symIndex = next((i for i,v in enumerate(data) if v['sym'] == True), None) + + # finds the index on the local data array of the first bit + # with a symmetric pair with different value or None if does not exist such bit + asymIndex = next((i for i,v in enumerate(data) if v['sym'] == False), None) + + # sym refers to the bit with symmetric pair with equal value + # asym refers to the bit with symmetric pair with different value + + # symB and asymB will store the new values of the known bits after fluctuation + + # dSym and dAsym will store a boolean of wether the known bits changed + # after the fluctuation + + symB = asymB = dSym = dAsym = None + + if symIndex is not None: + symB = getBit(symIndex+1) + dSym = data[symIndex]['val'] != symB + else: + getBit(1) + if asymIndex is not None: + asymB = getBit(asymIndex+1) + dAsym = data[asymIndex]['val'] != asymB + else: + getBit(1) + + if (symB is not None) and (asymB is not None): + if dSym and dAsym: + return "C" + elif (not dSym) and dAsym: + return "R" + elif dSym and (not dAsym): + return "CR" + elif (not dSym) and (not dAsym): + return None + elif (symB is not None) and (asymB is None): + if dSym: + return "C" + else: + return None + elif (symB is None) and (asymB is not None): + if dAsym: + return "C" + else: + return None + +def complement(data): + for d in data: + if d['val'] == '0': + d['val'] = '1' + elif d['val'] == '1': + d['val'] = '0' + +def update(data, fluctuationType): + if fluctuationType == "C": + complement(data) + elif fluctuationType == "R": + data.reverse() + elif fluctuationType == "CR": + complement(data) + data.reverse() + +# reads number of cases t and length of data array +t, b = (int(s) for s in input().split(' ')) +q = 0 # counts how many queries we have made so far + +for testCase in range(1, t + 1): + # creates a list of dicts to store bit values + # and info about wether the bit has a symmetrical pair + # with equal value or not + data = [ {'val': None, 'sym': None } for _ in range(b)] + for i in range(0, int(b/2)): + if q > 0 and q%10 == 0: + update(data, getFluctuationType(data)) + q += 2 + getPair(data, i, b) + q += 2 + r = "" + for dict in data: + r += dict['val'] + print(r) # attempts to give an answer about current bits in the data array + sys.stdout.flush() + ans = input() + q = 0 + if ans != 'Y': + break # if answer was incorrect no more processing is done \ No newline at end of file diff --git a/solutions/foregone-solution/README.md b/solutions/foregone-solution/README.md new file mode 100644 index 00000000..29f31f38 --- /dev/null +++ b/solutions/foregone-solution/README.md @@ -0,0 +1,7 @@ +# Foregone Solution + +Someone just won the Code Jam lottery, and we owe them N jamcoins! However, when we tried to print out an oversized check, we encountered a problem. The value of N, which is an integer, includes at least one digit that is a 4... and the 4 key on the keyboard of our oversized check printer is broken. + +Fortunately, we have a workaround: we will send our winner two checks for positive integer amounts A and B, such that neither A nor B contains any digit that is a 4, and A + B = N. Please help us find any pair of values A and B that satisfy these conditions. + +More details: https://codingcompetitions.withgoogle.com/codejam/round/0000000000051705/0000000000088231 diff --git a/solutions/foregone-solution/go/foregone-solution.go b/solutions/foregone-solution/go/foregone-solution.go new file mode 100644 index 00000000..24c26a1d --- /dev/null +++ b/solutions/foregone-solution/go/foregone-solution.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" + "strconv" +) + +// Just for the reading of the test cases +func main(){ + var T int + fmt.Scanf("%d", &T) + for caseNumber := 1; caseNumber <= T ; caseNumber++{ + A, B := foregone() + fmt.Printf("Case #%d: %s %s\n", caseNumber, A, B) + } + +} + +// The solution of the actual problem +func foregone() (A, B string) { + var N string + fmt.Scanf("%s", &N) + var four string = strconv.Itoa(4) + A = "" + B = "" + + for _, char := range N { + if c := string(char); four == c { + A += "2" + B += "2" + } else { + A += c + B += "0" + } + } + + return +} \ No newline at end of file diff --git a/solutions/foregone-solution/java/foregone-solution.java b/solutions/foregone-solution/java/foregone-solution.java new file mode 100644 index 00000000..86cef9c8 --- /dev/null +++ b/solutions/foregone-solution/java/foregone-solution.java @@ -0,0 +1,30 @@ +import java.util.Scanner; +public class Foregone { + public static void main(String[] args) { + Scanner input = new Scanner(System.in); + int t = input.nextInt(); + + for (int i = 1; i <= t; i++ ) { + String n = input.next(); + foregoneAlgorithm(i, n); + } + input.close(); + } + public static void foregoneAlgorithm(int t, String n) { + String[] substrings = n.split(""); + + String a = ""; + String b = ""; + + for(String i : substrings) { + if (i.equals("4")){ + a = a.concat("2"); + b = b.concat("2"); + } else { + a = a.concat(i); + b = b.concat("0"); + } + } + System.out.println("Case #"+ t + ": " + a + " " + b); + } +} diff --git a/solutions/foregone-solution/lisp/foregone-solution.lisp b/solutions/foregone-solution/lisp/foregone-solution.lisp new file mode 100644 index 00000000..28048fb5 --- /dev/null +++ b/solutions/foregone-solution/lisp/foregone-solution.lisp @@ -0,0 +1,38 @@ +;;; Function that calculates the amount for each check +(defun get-check-amounts(num) + (let ((a nil)) ; Create a local variable for the check a + (let ((b nil)) ; Create a local variable for the check b + + (loop for c across num do ; Loop across the string + (if (string= c "4") ; If we find a 4 + (progn + (setf a (cons '2 a)) ; We add a 2 to list a + (setf b (cons '2 b)) ; We add a 2 to list b + ) + (progn ; If we dont find a 4 + (setf a (cons c a)) ; We add the number to list a + (if b ; If b doesnt have a value + ; We check this, so that there are no leading 0s + (setf b (cons '0 b)) ; We add a 0 to list b + ) + ) + ) + ) + (values (reverse a) (reverse b)) ; We return both lists + )) +) + +;;; Function that solves a test case +(defun solve(casenum) + (let ((num (read-line))) ; Read number + (multiple-value-bind (a b) (get-check-amounts num) + (format t "Case #~d: ~{~d~} ~{~d~}~%" casenum a b)) +)) + +;;; Read the amount of test cases +(defvar *cases* (read)) + +;;; Run the solve function for each test case +(loop for x from 1 to *cases* do + (solve x) +) \ No newline at end of file diff --git a/solutions/foregone-solution/python/foregone-solution.py b/solutions/foregone-solution/python/foregone-solution.py new file mode 100644 index 00000000..1f40025f --- /dev/null +++ b/solutions/foregone-solution/python/foregone-solution.py @@ -0,0 +1,16 @@ +## input: +# T: number of test cases +# N: for each test case, N is the number of jamcoins, has at least a 4 +## output: +# A,B: Two integers that have no 4's and A+B = N + +T = int(input()) + +for j in range(T): + N = input() + idx = -1 + A = 0 + for i in range(N.count('4') ): # get each 4 position + idx = N.find('4', idx + 1, len(N)) + A = A + 2*10**(len(N)-idx-1) # Set a 2 in said position in A, it will have a 0 if it is not a 4 in N + print('Case #%d: %d %d'%((j+1),(int(N) - A), A)) # Return A and B = N - A \ No newline at end of file diff --git a/solutions/nesting-depth/README.md b/solutions/nesting-depth/README.md new file mode 100644 index 00000000..104b19e9 --- /dev/null +++ b/solutions/nesting-depth/README.md @@ -0,0 +1,16 @@ +# Nesting Depth + +Given a string of digits S, insert a minimum number of opening and closing parentheses into it such that the resulting string is balanced and each digit d is inside exactly d pairs of matching parentheses. + +Let the nesting of two parentheses within a string be the substring that occurs strictly between them. An opening parenthesis and a closing parenthesis that is further to its right are said to match if their nesting is empty, or if every parenthesis in their nesting matches with another parenthesis in their nesting. The nesting depth of a position p is the number of pairs of matching parentheses m such that p is included in the nesting of m. + +For example, in the following strings, all digits match their nesting depth: 0((2)1), (((3))1(2)), ((((4)))), ((2))((2))(1). The first three strings have minimum length among those that have the same digits in the same order, but the last one does not since ((22)1) also has the digits 221 and is shorter. + +Given a string of digits S, find another string S', comprised of parentheses and digits, such that: + +- all parentheses in S' match some other parenthesis +- removing any and all parentheses from S' results in S +- each digit in S' is equal to its nesting depth +- S' is of minimum length + +More details: https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd27/0000000000209a9f diff --git a/solutions/nesting-depth/go/nesting-depth.go b/solutions/nesting-depth/go/nesting-depth.go new file mode 100644 index 00000000..d79119fd --- /dev/null +++ b/solutions/nesting-depth/go/nesting-depth.go @@ -0,0 +1,52 @@ +package main + +import ( + "fmt" + "math" + "strconv" +) + +// Just for the testcases +func main() { + var T int + fmt.Scanf("%d", &T) + for caseNumber := 1; caseNumber <= T; caseNumber++ { + S := nestingDepth() + fmt.Printf("Case #%d: %s\n", caseNumber, S) + } +} + +// The solution +func nestingDepth() (nestingS string) { + var S string + var parentesisAbiertos int = 0 + fmt.Scanf("%s", &S) + + nestingS = "" + + for _, val := range S { + char := string(val) + + if digit, _ := strconv.Atoi(char); parentesisAbiertos == digit { + nestingS += char + } else if remain := digit - parentesisAbiertos; remain > 0 { + for i := 0; i < remain; i++ { + nestingS += "(" + parentesisAbiertos++ + } + nestingS += char + } else { + for i := 0; i < int(math.Abs(float64(remain))); i++ { + nestingS += ")" + parentesisAbiertos-- + } + nestingS += char + } + } + + for i := 0; i < parentesisAbiertos; i++ { + nestingS += ")" + } + + return +} diff --git a/solutions/nesting-depth/java/nesting-depth.java b/solutions/nesting-depth/java/nesting-depth.java new file mode 100644 index 00000000..924f9f23 --- /dev/null +++ b/solutions/nesting-depth/java/nesting-depth.java @@ -0,0 +1,79 @@ +import java.util.Scanner; + +public class NestingDepth { + public static void main(String[] args) { + Scanner input = new Scanner(System.in); + int t = input.nextInt(); + + for (int i = 1; i <= t; i++ ) { + String n = input.next(); + nestingAlgorithm(i, n); + } + input.close(); + } + + public static void nestingAlgorithm(int t, String s) { + s = "0" + s + "0"; + String[] substrings = s.split(""); + + String[] newArray = substrings; + + int count = 0; + + for(int i = 1; i < substrings.length; i++) { + int dif = substrings[i].compareTo(substrings[i-1]); + int abs = Math.abs(dif); + int index = i + count; + + if (dif > 0) { + newArray = addOpeningParenthesis(newArray, index, abs); + count++; + } else if (dif < 0){ + newArray = addClosingParenthesis(newArray, index, abs); + count++; + } + + } + + String result = String.join("", newArray); + result = result.substring(1, result.length()-1); + + System.out.println("Case #"+ t + ": " + result); + } + + public static String[] addClosingParenthesis(String[] array, int index, int times) { + String parenthesis = ")".repeat(times); + String[] newArray = new String[array.length + 1]; + + int j = 0; + + for(int i = 0; i < newArray.length; i++) { + if(i == index) { + newArray[i] = parenthesis; + }else { + newArray[i] = array[j]; + j++; + } + } + + return newArray; + } + + public static String[] addOpeningParenthesis(String[] array, int index, int times) { + String parenthesis = "(".repeat(times); + String[] newArray = new String[array.length + 1]; + + int j = 0; + + for(int i = 0; i < newArray.length; i++) { + if(i == index) { + newArray[i] = parenthesis; + }else { + newArray[i] = array[j]; + j++; + } + } + + return newArray; + } +} diff --git a/solutions/nesting-depth/lisp/nesting-depth.lisp b/solutions/nesting-depth/lisp/nesting-depth.lisp new file mode 100644 index 00000000..89e33042 --- /dev/null +++ b/solutions/nesting-depth/lisp/nesting-depth.lisp @@ -0,0 +1,30 @@ +(defun add_parenthesis (parenthesis s) + "If parenthesis > 0 adds '(' parenthesis times. If < 0 adds ')' parenthesis times. + If parenthesis equals 0 return the unmodified string" + (cond ((zerop parenthesis) s) + ((plusp parenthesis) (add_parenthesis (1- parenthesis) (concatenate 'string s "("))) + ((minusp parenthesis) (add_parenthesis (1+ parenthesis) (concatenate 'string s ")"))))) + +(defun nesting_depth (number_string final_string open_parenthesis) + "Given a string of digits S, insert a minimum number of opening and closing parentheses + into it such that the resulting string is balanced and each digit d is inside exactly d + pairs of matching parentheses." + (if (equal number_string "") + (add_parenthesis (* -1 open_parenthesis) final_string) ;; Close the last opened parenthesis + (let* ((digit_number (digit-char-p (char number_string 0))) + (digit_string (write-to-string digit_number))) + (if (= digit_number open_parenthesis) ;; open parenthesis match the digit, hence concatenates the digit + (nesting_depth (subseq number_string 1) + (concatenate 'string final_string digit_string) + digit_number) + (nesting_depth (subseq number_string 1) ;; parnthesis needs to be open or close before concatenating the digit + (concatenate 'string (add_parenthesis (- digit_number open_parenthesis) + final_string) + digit_string) + digit_number))))) + +(defun main () + (loop for test from 1 to (parse-integer (read-line)) do + (setf result (nesting_depth (read-line) "" 0)) + (format t "Case #~d: ~d~%" test result))) +(main) \ No newline at end of file diff --git a/solutions/nesting-depth/python/nesting-depth.py b/solutions/nesting-depth/python/nesting-depth.py new file mode 100644 index 00000000..b9d78dfc --- /dev/null +++ b/solutions/nesting-depth/python/nesting-depth.py @@ -0,0 +1,36 @@ +"""Nesting Depth + +This is a solution for the Google Code Jam 'Nesting Depth' problem +Given a string of digits S, insert a minimum number of opening and +closing parentheses into it such that the resulting string +is balanced and each digit d is inside exactly d pairs of matching parentheses + +The first line of the input gives the number of test cases, T. +T lines follow. Each line represents a test case and contains only the string S + +More information: +https://codingcompetitions.withgoogle.com/ + codejam/round/000000000019fd27/0000000000209a9f +""" + +def solve(s): + s = '0' + s + '0' + diff = 0 + i = 1 + while i < len(s): + # inserts parenthesis based on difference between digits + diff = int(s[i]) - int(s[i-1]) + if diff > 0: + s = s[:i] + ('(' * abs(diff)) + s[i:] + elif diff < 0: + s = s[:i] + (')' * abs(diff)) + s[i:] + + # next iteration will be next digit and not a parenthesis + i += abs(diff) + 1 + + return s[1:-1] # remove extra zeros added at the beginning + +t = int(input()) + +for i in range(1, t + 1): + print(f'Case #{i}: {solve(input())}') diff --git a/solutions/you-can-go-your-own-way/README.md b/solutions/you-can-go-your-own-way/README.md new file mode 100644 index 00000000..2a5b8d1a --- /dev/null +++ b/solutions/you-can-go-your-own-way/README.md @@ -0,0 +1,9 @@ +# You Can Go Your Own Way + +You have just entered the world's easiest maze. You start in the northwest cell of an N by N grid of unit cells, and you must reach the southeast cell. You have only two types of moves available: a unit move to the east, and a unit move to the south. You can move into any cell, but you may not make a move that would cause you to leave the grid. + +You are excited to be the first in the world to solve the maze, but then you see footprints. Your rival, Labyrinth Lydia, has already solved the maze before you, using the same rules described above! + +As an original thinker, you do not want to reuse any of Lydia's moves. Specifically, if her path includes a unit move from some cell A to some adjacent cell B, your path cannot also include a move from A to B. (However, in that case, it is OK for your path to visit A or visit B, as long as you do not go from A to B.) Please find such a path. + +More details: https://codingcompetitions.withgoogle.com/codejam/round/0000000000051705/00000000000881da diff --git a/solutions/you-can-go-your-own-way/go/you-can-go-your-own-way.go b/solutions/you-can-go-your-own-way/go/you-can-go-your-own-way.go new file mode 100644 index 00000000..69c1ca9e --- /dev/null +++ b/solutions/you-can-go-your-own-way/go/you-can-go-your-own-way.go @@ -0,0 +1,36 @@ +package main + +import ( + "bufio" + "fmt" + . "fmt" + . "os" +) + +var rd *bufio.Reader = bufio.NewReader(Stdin) +var wr *bufio.Writer = bufio.NewWriter(Stdout) + +func main() { + var T, N int + var S string + + Scanf("%d", &T) + + for i := 1; i <= T; i++ { + var sol string + sol = "" + Scanf("%d", &N) + Scanf("%s", &S) + + for _, ch := range S { + if ch == 83 { + sol += "E" + } else { + sol += "S" + } + } + fmt.Printf("Case #%d: %s\n", i, sol) + defer wr.Flush() + } + +} diff --git a/solutions/you-can-go-your-own-way/java/you-can-go-your-own-way.java b/solutions/you-can-go-your-own-way/java/you-can-go-your-own-way.java new file mode 100644 index 00000000..db851bb7 --- /dev/null +++ b/solutions/you-can-go-your-own-way/java/you-can-go-your-own-way.java @@ -0,0 +1,32 @@ +import java.util.Scanner; + +class Solution { + + public static void main(String[] args){ + Scanner input = new Scanner(System.in); + int t = input.nextInt(); + + for (int i=1; i<=t; i++) { + int n = input.nextInt(); + String s = input.next(); + resolve(i, n, s); + } + + input.close(); + } + + public static void resolve(int t, int n, String s) { + StringBuffer newStr = new StringBuffer(s); + + for(int i = 0; i < s.length(); i++){ + if(s.charAt(i) == 'S' || s.charAt(i) == 's'){ + newStr.setCharAt(i, 'E'); + } else if(s.charAt(i) == 'E' || s.charAt(i) == 'e'){ + newStr.setCharAt(i, 'S'); + } + } + + + System.out.println("Case #" + t + ": " + newStr); + } +} diff --git a/solutions/you-can-go-your-own-way/lisp/you-can-go-your-own-way.lisp b/solutions/you-can-go-your-own-way/lisp/you-can-go-your-own-way.lisp new file mode 100644 index 00000000..6ea8c49e --- /dev/null +++ b/solutions/you-can-go-your-own-way/lisp/you-can-go-your-own-way.lisp @@ -0,0 +1,26 @@ +;;; Function that swaps all S's with E's and vice versa +(defun invert-path(path) + (let ((new-path nil)) ; Create a local variable for new list + (loop for c across path do ; Loop across Lydia's path + (if (string= c "S") ; If the char is an "S" + (setf new-path (cons 'E new-path)) ; Add an E to the list + (setf new-path (cons 'S new-path)) ; If not, add an S to the list + ) + ) + (return-from invert-path (reverse new-path)) ; Return new list +)) + +;;; Function that solves a test case +(defun solve(casenum) + (let ((maze-size (read))) ; Read the maze size + (let ((path (read-line))) ; Read Lydia's path + (format t "Case #~d: ~{~d~}~%" casenum (invert-path path)) +))) + +;;; Read the amount of test cases +(defvar *cases* (read)) + +;;; Run the solve function for each test case +(loop for x from 1 to *cases* do + (solve x) +) \ No newline at end of file diff --git a/solutions/you-can-go-your-own-way/python/you-can-go-your-own-way.py b/solutions/you-can-go-your-own-way/python/you-can-go-your-own-way.py new file mode 100644 index 00000000..f870e3c9 --- /dev/null +++ b/solutions/you-can-go-your-own-way/python/you-can-go-your-own-way.py @@ -0,0 +1,19 @@ + +## input: +# T: number of test cases +# N: grid will have NxN size +# y: String that represents Lydia's path, it has N-1 characters +## output: +# path that will not have a step as Lydias' one +T = int(input()) # numero de casos de prueba + +for j in range(T): + N = input() #ni siquiera voy a usar esta variable + y = input() + sol = "" + for l in y: # for each step in Lydia's Path, we take the opposite step + if l == 'S': + sol = sol + 'E' + else: + sol = sol + 'S' + print('Case #%d: %s'%((j+1),sol)) # return new path \ No newline at end of file