├── .DS_Store ├── .gitignore ├── .vscode ├── keybindings.json └── settings.json ├── README.md └── input ├── week1_programming_challenges ├── 1_sum_of_two_digits │ ├── APlusB.cpp │ ├── APlusB.cs │ ├── APlusB.hs │ ├── APlusB.java │ ├── APlusB.js │ ├── APlusB.kt │ ├── APlusB.py │ ├── APlusB.rb │ ├── APlusB.rs │ └── APlusB.scala ├── 2_maximum_pairwise_product │ ├── MaxPairwiseProduct.java │ ├── MaxPairwiseProduct.kt │ ├── a.out │ ├── by_learners │ │ └── max_pairwise_product.rb │ ├── max_pairwise_product.cpp │ └── max_pairwise_product.py └── week1_programming_challenges.pdf ├── week2_algorithmic_warmup ├── .DS_Store ├── 1_fibonacci_number │ ├── Fibonacci.java │ ├── Fibonacci.kt │ ├── by_learners │ │ └── fibonacci.rb │ ├── fibonacci.cpp │ ├── fibonacci.hs │ └── fibonacci.py ├── 2_last_digit_of_fibonacci_number │ ├── FibonacciLastDigit.java │ ├── FibonacciLastDigit.kt │ ├── by_learners │ │ └── fibonacci_last_digit.rb │ ├── fibonacci_last_digit.cpp │ ├── fibonacci_last_digit.hs │ └── fibonacci_last_digit.py ├── 3_greatest_common_divisor │ ├── GCD.java │ ├── GCD.kt │ ├── by_learners │ │ └── gcd.rb │ ├── gcd.cpp │ ├── gcd.hs │ └── gcd.py ├── 4_least_common_multiple │ ├── LCM.java │ ├── LCM.kt │ ├── by_learners │ │ └── lcm.rb │ ├── lcm.cpp │ ├── lcm.hs │ └── lcm.py ├── 5_fibonacci_number_again │ ├── FibonacciHuge.java │ ├── FibonacciHuge.kt │ ├── by_learners │ │ └── fibonacci_huge.rb │ ├── fibonacci_huge.cpp │ ├── fibonacci_huge.hs │ └── fibonacci_huge.py ├── 6_last_digit_of_the_sum_of_fibonacci_numbers │ ├── FibonacciSumLastDigit.java │ ├── FibonacciSumLastDigit.kt │ ├── by_learners │ │ └── fibonacci_sum_last_digit.rb │ ├── fibonacci_sum_last_digit.cpp │ ├── fibonacci_sum_last_digit.hs │ └── fibonacci_sum_last_digit.py ├── 7_last_digit_of_the_sum_of_fibonacci_numbers_again │ ├── FibonacciPartialSum.java │ ├── FibonacciPartialSum.kt │ ├── by_learners │ │ └── fib_partial_sum.rb │ ├── fibonacci_partial_sum.cpp │ ├── fibonacci_partial_sum.hs │ └── fibonacci_partial_sum.py ├── 8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers │ ├── FibonacciSumSquares.java │ ├── fibonacci_sum_squares.cpp │ └── fibonacci_sum_squares.py └── week2_algorithmic_warmup.pdf ├── week3_greedy_algorithms ├── .DS_Store ├── 1_money_change │ ├── Change.java │ ├── Change.kt │ ├── by_learners │ │ └── change.rb │ ├── change.cpp │ ├── change.hs │ └── change.py ├── 2_maximum_value_of_the_loot │ ├── FractionalKnapsack.java │ ├── FractionalKnapsack.kt │ ├── by_learners │ │ └── fractional_knapsack.rb │ ├── fractional_knapsack.cpp │ ├── fractional_knapsack.hs │ └── fractional_knapsack.py ├── 3_car_fueling │ ├── CarFueling.java │ ├── car_fueling.cpp │ └── car_fueling.py ├── 4_maximum_advertisement_revenue │ ├── DotProduct.java │ ├── DotProduct.kt │ ├── by_learners │ │ └── dot_rpoduct.rb │ ├── dot_product.cpp │ ├── dot_product.hs │ └── dot_product.py ├── 5_collecting_signatures │ ├── CoveringSegments.java │ ├── CoveringSegments.kt │ ├── by_learners │ │ └── covering_segments.rb │ ├── covering_segments.cpp │ ├── covering_segments.hs │ └── covering_segments.py ├── 6_maximum_number_of_prizes │ ├── DifferentSummands.java │ ├── DifferentSummands.kt │ ├── by_learners │ │ └── different_summands.rb │ ├── different_summands.cpp │ ├── different_summands.hs │ └── different_summands.py ├── 7_maximum_salary │ ├── LargestNumber.java │ ├── LargestNumber.kt │ ├── by_learners │ │ └── largest_number.rb │ ├── largest_number.cpp │ ├── largest_number.hs │ └── largest_number.py └── week3_greedy_algorithms.pdf ├── week4_divide_and_conquer ├── 1_binary_search │ ├── BinarySearch.java │ ├── BinarySearch.kt │ ├── binary_search.cpp │ ├── binary_search.py │ └── by_learners │ │ └── binary_search.rb ├── 2_majority_element │ ├── MajorityElement.java │ ├── MajorityElement.kt │ ├── by_learners │ │ └── majority_element.rb │ ├── majority_element.cpp │ └── majority_element.py ├── 3_improving_quicksort │ ├── Sorting.java │ ├── Sorting.kt │ ├── by_learners │ │ └── sorting.rb │ ├── sorting.cpp │ └── sorting.py ├── 4_number_of_inversions │ ├── Inversions.java │ ├── Inversions.kt │ ├── by_learners │ │ └── inversions.rb │ ├── inversions.cpp │ └── inversions.py ├── 5_organizing_a_lottery │ ├── PointsAndSegments.java │ ├── PointsAndSegments.kt │ ├── by_learners │ │ └── points_and_segments.rb │ ├── points_and_segments.cpp │ └── points_and_segments.py ├── 6_closest_points │ ├── Closest.java │ ├── Closest.kt │ ├── by_learners │ │ └── closest.rb │ ├── closest.cpp │ ├── closest.py │ └── closest_points.py └── week4_divide_and_conquer.pdf ├── week5_dynamic_programming1 ├── 1_money_change_again │ ├── ChangeDP.java │ ├── ChangeDP.kt │ ├── change_dp.cpp │ └── change_dp.py ├── 2_primitive_calculator │ ├── PrimitiveCalculator.java │ ├── PrimitiveCalculator.kt │ ├── by_learners │ │ └── primitive_calculator.rb │ ├── primitive_calculator.cpp │ └── primitive_calculator.py ├── 3_edit_distance │ ├── EditDistance.java │ ├── EditDistance.kt │ ├── by_learners │ │ └── edit_distance.rb │ ├── edit_distance.cpp │ └── edit_distance.py ├── 4_longest_common_subsequence_of_two_sequences │ ├── LCS2.java │ ├── LCS2.kt │ ├── lcs2.cpp │ └── lcs2.py ├── 5_longest_common_subsequence_of_three_sequences │ ├── LCS3.java │ ├── LCS3.kt │ ├── by_learners │ │ └── lcs3.rb │ ├── lcs3.cpp │ └── lcs3.py └── week5_dynamic_programming1.pdf └── week6_dynamic_programming2 ├── 1_maximum_amount_of_gold ├── Knapsack.java ├── Knapsack.kt ├── by_learners │ └── knapsack.rb ├── knapsack.cpp └── knapsack.py ├── 2_partitioning_souvenirs ├── Partition3.java ├── Partition3.kt ├── partition3.cpp └── partition3.py ├── 3_maximum_value_of_an_arithmetic_expression ├── PlacingParentheses.java ├── PlacingParentheses.kt ├── by_learners │ └── placing_parentheses.rb ├── placing_parentheses.cpp └── placing_parentheses.py └── week6_dynamic_programming2.pdf /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WillKoehrsen/data-structures-and-algorithms-coursera/d13b5460447d3decc095aa54b883e01d8c8a9860/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | *.DS_Store 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | .hypothesis/ 50 | .pytest_cache/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | local_settings.py 59 | db.sqlite3 60 | 61 | # Flask stuff: 62 | instance/ 63 | .webassets-cache 64 | 65 | # Scrapy stuff: 66 | .scrapy 67 | 68 | # Sphinx documentation 69 | docs/_build/ 70 | 71 | # PyBuilder 72 | target/ 73 | 74 | # Jupyter Notebook 75 | .ipynb_checkpoints 76 | 77 | # pyenv 78 | .python-version 79 | 80 | # celery beat schedule file 81 | celerybeat-schedule 82 | 83 | # SageMath parsed files 84 | *.sage.py 85 | 86 | # Environments 87 | .env 88 | .venv 89 | env/ 90 | venv/ 91 | ENV/ 92 | env.bak/ 93 | venv.bak/ 94 | 95 | # Spyder project settings 96 | .spyderproject 97 | .spyproject 98 | 99 | # Rope project settings 100 | .ropeproject 101 | 102 | # mkdocs documentation 103 | /site 104 | 105 | # mypy 106 | .mypy_cache/ 107 | -------------------------------------------------------------------------------- /.vscode/keybindings.json: -------------------------------------------------------------------------------- 1 | // Empty 2 | [ 3 | { 4 | "key": "shift+enter", 5 | "command": "macros.executeSelectedCode" 6 | }, 7 | // Toggle between terminal and editor focus 8 | { 9 | "key": "ctrl+`", 10 | "command": "workbench.action.terminal.focus" 11 | }, 12 | { 13 | "key": "ctrl+`", 14 | "command": "workbench.action.focusActiveEditorGroup", 15 | "when": "terminalFocus" 16 | }, 17 | ] -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "C:\\ProgramData\\Anaconda3\\python.exe", 3 | "editor.fontSize": 14, 4 | "editor.wordWrap": "wordWrapColumn", 5 | "editor.hover.delay": 100, 6 | "editor.parameterHints.cycle": true, 7 | "editor.tabCompletion": "on", 8 | "editor.acceptSuggestionOnEnter": "off", 9 | "files.trimTrailingWhitespace": true, 10 | "window.restoreWindows": "folders", 11 | "window.openFoldersInNewWindow": "on", 12 | "window.openFilesInNewWindow": "on", 13 | "python.disableInstallationCheck": true, 14 | "python.linting.flake8Enabled": true, 15 | "workbench.editor.enablePreviewFromQuickOpen": false, 16 | "workbench.editor.enablePreview": false, 17 | "terminal.integrated.confirmOnExit": true, 18 | "terminal.integrated.cursorBlinking": true, 19 | "terminal.integrated.fontSize": 16, 20 | "python.linting.pylintEnabled": false, 21 | "python.linting.pylintUseMinimalCheckers": false, 22 | "python.testing.pytestEnabled": true, 23 | "python.jediEnabled": false, 24 | "editor.renderWhitespace": "none", 25 | "window.zoomLevel": 0, 26 | "editor.largeFileOptimizations": false, 27 | "editor.formatOnSave": true, 28 | "python.formatting.autopep8Args": [ 29 | "--max-line-length", 30 | "88", 31 | "--ignore", 32 | "E402", 33 | ], 34 | "editor.minimap.enabled": false, 35 | "workbench.colorTheme": "Monokai Dimmed", 36 | "editor.wordWrapColumn": 88, 37 | "kite.showWelcomeNotificationOnStartup": false, 38 | "editor.suggestSelection": "first", 39 | "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue", 40 | "python.formatting.provider": "black", 41 | "python.linting.enabled": true, 42 | "files.autoSave": "afterDelay", 43 | "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\git-cmd.exe", 44 | "python.dataScience.sendSelectionToInteractiveWindow": true, 45 | "python.terminal.executeInFileDir": true, 46 | "macros": { 47 | "executeSelectedCode": [ 48 | "workbench.action.terminal.runSelectedText", 49 | "workbench.action.terminal.focus", 50 | ] 51 | } 52 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # data-structures-and-algorithms-coursera 2 | Materials and assignments for Coursera Course: data structures and algorithms 3 | -------------------------------------------------------------------------------- /input/week1_programming_challenges/1_sum_of_two_digits/APlusB.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int sum_of_two_digits(int first_digit, int second_digit) { 4 | return first_digit + second_digit; 5 | } 6 | 7 | int main() { 8 | int a = 0; 9 | int b = 0; 10 | std::cin >> a; 11 | std::cin >> b; 12 | std::cout << sum_of_two_digits(a, b); 13 | return 0; 14 | } -------------------------------------------------------------------------------- /input/week1_programming_challenges/1_sum_of_two_digits/APlusB.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace APlusB 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | var input = Console.ReadLine(); 10 | var tokens = input.Split(' '); 11 | var a = int.Parse(tokens[0]); 12 | var b = int.Parse(tokens[1]); 13 | Console.WriteLine(a + b); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /input/week1_programming_challenges/1_sum_of_two_digits/APlusB.hs: -------------------------------------------------------------------------------- 1 | 2 | main = do 3 | s <- getLine 4 | let w = words s 5 | readInt :: String -> Int 6 | readInt = read 7 | x = map readInt w 8 | t = sum x 9 | putStrLn $ show t 10 | -------------------------------------------------------------------------------- /input/week1_programming_challenges/1_sum_of_two_digits/APlusB.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class APlusB { 4 | static int sumOfTwoDigits(int first_digit, int second_digit) { 5 | return first_digit + second_digit; 6 | } 7 | 8 | public static void main(String[] args) { 9 | Scanner s = new Scanner(System.in); 10 | int a = s.nextInt(); 11 | int b = s.nextInt(); 12 | System.out.println(sumOfTwoDigits(a, b)); 13 | } 14 | } -------------------------------------------------------------------------------- /input/week1_programming_challenges/1_sum_of_two_digits/APlusB.js: -------------------------------------------------------------------------------- 1 | var readline = require('readline'); 2 | 3 | process.stdin.setEncoding('utf8'); 4 | var rl = readline.createInterface({ 5 | input: process.stdin, 6 | terminal: false 7 | }); 8 | 9 | rl.on('line', readLine); 10 | 11 | function readLine (line) { 12 | if (line !== "\n") { 13 | var a = parseInt(line.toString().split(' ')[0], 10); 14 | var b = parseInt(line.toString().split(' ')[1], 10); 15 | console.log(a + b); 16 | process.exit(); 17 | } 18 | } -------------------------------------------------------------------------------- /input/week1_programming_challenges/1_sum_of_two_digits/APlusB.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun main(args: Array) { 4 | val s = Scanner(System.`in`) 5 | val a = s.nextInt() 6 | val b = s.nextInt() 7 | println(a + b) 8 | } -------------------------------------------------------------------------------- /input/week1_programming_challenges/1_sum_of_two_digits/APlusB.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | 4 | def sum_of_two_digits(first_digit, second_digit): 5 | return first_digit + second_digit 6 | 7 | 8 | if __name__ == "__main__": 9 | a, b = map(int, input().split()) 10 | print(sum_of_two_digits(a, b)) 11 | -------------------------------------------------------------------------------- /input/week1_programming_challenges/1_sum_of_two_digits/APlusB.rb: -------------------------------------------------------------------------------- 1 | a, b = gets.split(' ') 2 | puts a.to_i + b.to_i -------------------------------------------------------------------------------- /input/week1_programming_challenges/1_sum_of_two_digits/APlusB.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut buff = String::new(); 3 | ::std::io::stdin().read_line(&mut buff); 4 | let mut words = buff.split_whitespace(); 5 | 6 | let a: i64 = words.next().unwrap().parse().unwrap(); 7 | let b: i64 = words.next().unwrap().parse().unwrap(); 8 | 9 | println!("{}", a + b); 10 | } 11 | -------------------------------------------------------------------------------- /input/week1_programming_challenges/1_sum_of_two_digits/APlusB.scala: -------------------------------------------------------------------------------- 1 | // by Guillaume Guy 2 | 3 | object APlusB extends App { 4 | override def main(args: Array[String]): Unit = { 5 | val scanner = new java.util.Scanner(System.in) 6 | val line = scanner.nextLine() 7 | val result = (line.split(" ").map( x => BigInt(x)) take 2).sum 8 | System.out.print(result ) 9 | 10 | } 11 | } -------------------------------------------------------------------------------- /input/week1_programming_challenges/2_maximum_pairwise_product/MaxPairwiseProduct.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class MaxPairwiseProduct { 5 | static int getMaxPairwiseProduct(int[] numbers) { 6 | int max_product = 0; 7 | int n = numbers.length; 8 | 9 | for (int first = 0; first < n; ++first) { 10 | for (int second = first + 1; second < n; ++second) { 11 | max_product = max(max_product, 12 | numbers[first] * numbers[second]) 13 | } 14 | } 15 | 16 | return max_product; 17 | } 18 | 19 | public static void main(String[] args) { 20 | FastScanner scanner = new FastScanner(System.in); 21 | int n = scanner.nextInt(); 22 | int[] numbers = new int[n]; 23 | for (int i = 0; i < n; i++) { 24 | numbers[i] = scanner.nextInt(); 25 | } 26 | System.out.println(getMaxPairwiseProduct(numbers)); 27 | } 28 | 29 | static class FastScanner { 30 | BufferedReader br; 31 | StringTokenizer st; 32 | 33 | FastScanner(InputStream stream) { 34 | try { 35 | br = new BufferedReader(new 36 | InputStreamReader(stream)); 37 | } catch (Exception e) { 38 | e.printStackTrace(); 39 | } 40 | } 41 | 42 | String next() { 43 | while (st == null || !st.hasMoreTokens()) { 44 | try { 45 | st = new StringTokenizer(br.readLine()); 46 | } catch (IOException e) { 47 | e.printStackTrace(); 48 | } 49 | } 50 | return st.nextToken(); 51 | } 52 | 53 | int nextInt() { 54 | return Integer.parseInt(next()); 55 | } 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /input/week1_programming_challenges/2_maximum_pairwise_product/MaxPairwiseProduct.kt: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader 2 | import java.io.IOException 3 | import java.io.InputStream 4 | import java.io.InputStreamReader 5 | import java.util.* 6 | 7 | fun getMaxPairwiseProduct(numbers: IntArray): Int { 8 | var result = 0 9 | val n = numbers.size 10 | for (i in 0 until n) { 11 | for (j in i + 1 until n) { 12 | if (numbers[i] * numbers[j] > result) { 13 | result = numbers[i] * numbers[j] 14 | } 15 | } 16 | } 17 | return result 18 | } 19 | 20 | fun main(args: Array) { 21 | val scanner = FastScanner(System.`in`) 22 | val n = scanner.nextInt() 23 | val numbers = IntArray(n) 24 | for (i in 0 until n) { 25 | numbers[i] = scanner.nextInt() 26 | } 27 | println(getMaxPairwiseProduct(numbers)) 28 | } 29 | 30 | class FastScanner(stream: InputStream) { 31 | var br: BufferedReader = BufferedReader(InputStreamReader(stream)) 32 | var st: StringTokenizer? = null 33 | 34 | fun next(): String { 35 | while (st == null || !st!!.hasMoreTokens()) { 36 | try { 37 | st = StringTokenizer(br.readLine()) 38 | } catch (e: IOException) { 39 | e.printStackTrace() 40 | } 41 | } 42 | return st!!.nextToken() 43 | } 44 | 45 | fun nextInt() = next().toInt() 46 | } -------------------------------------------------------------------------------- /input/week1_programming_challenges/2_maximum_pairwise_product/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WillKoehrsen/data-structures-and-algorithms-coursera/d13b5460447d3decc095aa54b883e01d8c8a9860/input/week1_programming_challenges/2_maximum_pairwise_product/a.out -------------------------------------------------------------------------------- /input/week1_programming_challenges/2_maximum_pairwise_product/by_learners/max_pairwise_product.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def max_pairwise_product(a) 5 | # naive implementation 6 | # replace it 7 | result = 0 8 | n = a.size 9 | (0..n-1).each do |i| 10 | (i+1..n-1).each do |j| 11 | if a[i]*a[j] > result 12 | result = a[i]*a[j] 13 | end 14 | end 15 | end 16 | result 17 | end 18 | 19 | if __FILE__ == $0 20 | data = STDIN.read.split().map(&:to_i) 21 | n = data[0] 22 | a = data[1..n] 23 | puts "#{max_pairwise_product(a)}" 24 | end -------------------------------------------------------------------------------- /input/week1_programming_challenges/2_maximum_pairwise_product/max_pairwise_product.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | long long MaxPairwiseProduct(const std::vector& numbers) { 6 | long long max_product = 0; 7 | int n = numbers.size(); 8 | 9 | for (int first = 0; first < n; ++first) { 10 | for (int second = first + 1; second < n; ++second) { 11 | max_product = std::max(max_product, 12 | numbers[first] * numbers[second]); 13 | } 14 | } 15 | 16 | return max_product; 17 | } 18 | 19 | int main() { 20 | int n; 21 | std::cin >> n; 22 | std::vector numbers(n); 23 | for (int i = 0; i < n; ++i) { 24 | std::cin >> numbers[i]; 25 | } 26 | 27 | std::cout << MaxPairwiseProduct(numbers); 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /input/week1_programming_challenges/2_maximum_pairwise_product/max_pairwise_product.py: -------------------------------------------------------------------------------- 1 | # python3 2 | 3 | 4 | def max_pairwise_product(numbers): 5 | n = len(numbers) 6 | max_product = 0 7 | for first in range(n): 8 | for second in range(first + 1, n): 9 | max_product = max(max_product, numbers[first] * numbers[second]) 10 | 11 | return max_product 12 | 13 | 14 | if __name__ == "__main__": 15 | input_n = int(input()) 16 | input_numbers = [int(x) for x in input().split()] 17 | print(max_pairwise_product(input_numbers)) 18 | -------------------------------------------------------------------------------- /input/week1_programming_challenges/week1_programming_challenges.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WillKoehrsen/data-structures-and-algorithms-coursera/d13b5460447d3decc095aa54b883e01d8c8a9860/input/week1_programming_challenges/week1_programming_challenges.pdf -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WillKoehrsen/data-structures-and-algorithms-coursera/d13b5460447d3decc095aa54b883e01d8c8a9860/input/week2_algorithmic_warmup/.DS_Store -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/1_fibonacci_number/Fibonacci.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Fibonacci { 4 | private static long calc_fib(int n) { 5 | if (n <= 1) 6 | return n; 7 | 8 | return calc_fib(n - 1) + calc_fib(n - 2); 9 | } 10 | 11 | public static void main(String args[]) { 12 | Scanner in = new Scanner(System.in); 13 | int n = in.nextInt(); 14 | 15 | System.out.println(calc_fib(n)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/1_fibonacci_number/Fibonacci.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun calcFib(n: Long): Long { 4 | return if (n <= 1) n else calcFib(n - 1) + calcFib(n - 2) 5 | } 6 | 7 | fun main(args: Array) { 8 | val scanner = Scanner(System.`in`) 9 | val n = scanner.nextLong() 10 | 11 | println(calcFib(n)) 12 | } -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/1_fibonacci_number/by_learners/fibonacci.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def calc_fib(n) 5 | return n if n <= 1 6 | # slow 7 | # fix me 8 | calc_fib(n - 1) + calc_fib(n - 2) 9 | end 10 | 11 | if __FILE__ == $0 12 | n = gets.to_i 13 | puts "#{calc_fib(n)}" 14 | end 15 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // The following code calls a naive algorithm for computing a Fibonacci number. 5 | // 6 | // What to do: 7 | // 1. Compile the following code and run it on an input "40" to check that it is slow. 8 | // You may also want to submit it to the grader to ensure that it gets the "time limit exceeded" message. 9 | // 2. Implement the fibonacci_fast procedure. 10 | // 3. Remove the line that prints the result of the naive algorithm, comment the lines reading the input, 11 | // uncomment the line with a call to test_solution, compile the program, and run it. 12 | // This will ensure that your efficient algorithm returns the same as the naive one for small values of n. 13 | // 4. If test_solution() reveals a bug in your implementation, debug it, fix it, and repeat step 3. 14 | // 5. Remove the call to test_solution, uncomment the line with a call to fibonacci_fast (and the lines reading the input), 15 | // and submit it to the grader. 16 | 17 | int fibonacci_naive(int n) { 18 | if (n <= 1) 19 | return n; 20 | 21 | return fibonacci_naive(n - 1) + fibonacci_naive(n - 2); 22 | } 23 | 24 | int fibonacci_fast(int n) { 25 | // write your code here 26 | 27 | return 0; 28 | } 29 | 30 | void test_solution() { 31 | assert(fibonacci_fast(3) == 2); 32 | assert(fibonacci_fast(10) == 55); 33 | for (int n = 0; n < 20; ++n) 34 | assert(fibonacci_fast(n) == fibonacci_naive(n)); 35 | } 36 | 37 | int main() { 38 | int n = 0; 39 | std::cin >> n; 40 | 41 | std::cout << fibonacci_naive(n) << '\n'; 42 | //test_solution(); 43 | //std::cout << fibonacci_fast(n) << '\n'; 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.hs: -------------------------------------------------------------------------------- 1 | -- by Kirill Elagin 2 | 3 | import Control.Exception (assert) 4 | 5 | -- The following code calls a naive algorithm for computing a Fibonacci number. 6 | -- 7 | -- What to do: 8 | -- 1. Compile the following code and run it on an input "40" to check that it is slow. 9 | -- You may also want to submit it to the grader to ensure that it gets the "time limit exceeded" message. 10 | -- 2. Implement the fibonacci_fast procedure. 11 | -- 3. Remove the line that prints the result of the naive algorithm, comment the lines reading the input, 12 | -- uncomment the line with a call to test_solution, compile the program, and run it. 13 | -- This will ensure that your efficient algorithm returns the same as the naive one for small values of n. 14 | -- 4. If test_solution reveals a bug in your implementation, debug it, fix it, and repeat step 3. 15 | -- 5. Remove the call to test_solution, uncomment the line with a call to fibonacci_fast (and the lines reading the input), 16 | -- and submit it to the grader. 17 | 18 | fibonacci_naive :: Int -> Int 19 | fibonacci_naive 0 = 0 20 | fibonacci_naive 1 = 1 21 | fibonacci_naive n = fibonacci_naive (n - 1) + fibonacci_naive (n - 2) 22 | 23 | fibonacci_fast :: Int -> Int 24 | fibonacci_fast n = 0 -- write your code here 25 | 26 | test_solution :: IO () 27 | test_solution = and tests `seq` return () 28 | where 29 | tests = 30 | [ assert (fibonacci_fast 3 == 2) True 31 | , assert (fibonacci_fast 10 == 55) True 32 | ] ++ map (\i -> assert (fibonacci_fast i == fibonacci_naive i) True) [0..20] 33 | 34 | main :: IO () 35 | main = do 36 | [w] <- fmap words getLine 37 | let n = read w 38 | 39 | print $ fibonacci_naive n 40 | --test_solution 41 | --print $ fibonacci_fast n 42 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | def calc_fib(n): 3 | if n <= 1: 4 | return n 5 | 6 | return calc_fib(n - 1) + calc_fib(n - 2) 7 | 8 | 9 | def calc_fib_iter(n): 10 | if n <= 1: 11 | return n 12 | previous = 0 13 | current = 1 14 | for i in range(1, n): 15 | previous, current = current, previous + current 16 | return current 17 | 18 | 19 | n = int(input()) 20 | print(calc_fib_iter(n)) 21 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/2_last_digit_of_fibonacci_number/FibonacciLastDigit.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class FibonacciLastDigit { 4 | private static int getFibonacciLastDigitNaive(int n) { 5 | if (n <= 1) 6 | return n; 7 | 8 | int previous = 0; 9 | int current = 1; 10 | 11 | for (int i = 0; i < n - 1; ++i) { 12 | int tmp_previous = previous; 13 | previous = current; 14 | current = tmp_previous + current; 15 | } 16 | 17 | return current % 10; 18 | } 19 | 20 | public static void main(String[] args) { 21 | Scanner scanner = new Scanner(System.in); 22 | int n = scanner.nextInt(); 23 | int c = getFibonacciLastDigitNaive(n); 24 | System.out.println(c); 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/2_last_digit_of_fibonacci_number/FibonacciLastDigit.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun getFibonacciLastDigitNaive(n: Int): Int { 4 | if (n <= 1) 5 | return n 6 | 7 | var previous = 0 8 | var current = 1 9 | 10 | for (i in 0 until n - 1) { 11 | val tmpPrevious = previous 12 | previous = current 13 | current += tmpPrevious 14 | } 15 | 16 | return current % 10 17 | } 18 | 19 | fun main(args: Array) { 20 | val scanner = Scanner(System.`in`) 21 | val n = scanner.nextInt() 22 | val c = getFibonacciLastDigitNaive(n) 23 | println(c) 24 | } -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/2_last_digit_of_fibonacci_number/by_learners/fibonacci_last_digit.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def fib_last_digit(n) 5 | # fix me 6 | 0 7 | end 8 | 9 | if __FILE__ == $0 10 | n = gets.to_i 11 | puts "#{fib_last_digit(n)}" 12 | end -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/2_last_digit_of_fibonacci_number/fibonacci_last_digit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int get_fibonacci_last_digit_naive(int n) { 4 | if (n <= 1) 5 | return n; 6 | 7 | int previous = 0; 8 | int current = 1; 9 | 10 | for (int i = 0; i < n - 1; ++i) { 11 | int tmp_previous = previous; 12 | previous = current; 13 | current = tmp_previous + current; 14 | } 15 | 16 | return current % 10; 17 | } 18 | 19 | int main() { 20 | int n; 21 | std::cin >> n; 22 | int c = get_fibonacci_last_digit_naive(n); 23 | std::cout << c << '\n'; 24 | } 25 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/2_last_digit_of_fibonacci_number/fibonacci_last_digit.hs: -------------------------------------------------------------------------------- 1 | -- by Kirill Elagin 2 | 3 | fibonacci_last_digit :: Int -> Int 4 | fibonacci_last_digit = helper (0, 1) 5 | where 6 | helper (a, _) 0 = a `mod` 10 7 | helper (a, b) n = helper (b, a + b) (n - 1) 8 | 9 | main :: IO () 10 | main = do 11 | [n] <- fmap words getLine 12 | print $ fibonacci_last_digit (read n) 13 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/2_last_digit_of_fibonacci_number/fibonacci_last_digit.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | 5 | def get_fibonacci_last_digit_naive(n): 6 | if n <= 1: 7 | return n 8 | 9 | previous = 0 10 | current = 1 11 | 12 | for _ in range(n - 1): 13 | previous, current = current, (previous + current) % 10 14 | 15 | return current 16 | 17 | 18 | if __name__ == "__main__": 19 | input = sys.stdin.read() 20 | n = int(input) 21 | print(get_fibonacci_last_digit_naive(n)) 22 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/3_greatest_common_divisor/GCD.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class GCD { 4 | private static int gcd_naive(int a, int b) { 5 | int current_gcd = 1; 6 | for(int d = 2; d <= a && d <= b; ++d) { 7 | if (a % d == 0 && b % d == 0) { 8 | if (d > current_gcd) { 9 | current_gcd = d; 10 | } 11 | } 12 | } 13 | 14 | return current_gcd; 15 | } 16 | 17 | public static void main(String args[]) { 18 | Scanner scanner = new Scanner(System.in); 19 | int a = scanner.nextInt(); 20 | int b = scanner.nextInt(); 21 | 22 | System.out.println(gcd_naive(a, b)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/3_greatest_common_divisor/GCD.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun gcdNaive(a: Int, b: Int): Int { 4 | var currentGcd = 1 5 | var d = 2 6 | while (d <= a && d <= b) { 7 | if (a % d == 0 && b % d == 0) { 8 | if (d > currentGcd) { 9 | currentGcd = d 10 | } 11 | } 12 | ++d 13 | } 14 | 15 | return currentGcd 16 | } 17 | 18 | fun main(args: Array) { 19 | val scanner = Scanner(System.`in`) 20 | val a = scanner.nextInt() 21 | val b = scanner.nextInt() 22 | 23 | println(gcdNaive(a, b)) 24 | } -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/3_greatest_common_divisor/by_learners/gcd.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def gcd(a, b) 5 | # fix me 6 | a * b 7 | end 8 | 9 | if __FILE__ == $0 10 | a, b = gets.split().map(&:to_i) 11 | puts "#{gcd(a, b)}" 12 | end -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/3_greatest_common_divisor/gcd.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int gcd_naive(int a, int b) { 4 | int current_gcd = 1; 5 | for (int d = 2; d <= a && d <= b; d++) { 6 | if (a % d == 0 && b % d == 0) { 7 | if (d > current_gcd) { 8 | current_gcd = d; 9 | } 10 | } 11 | } 12 | return current_gcd; 13 | } 14 | 15 | int main() { 16 | int a, b; 17 | std::cin >> a >> b; 18 | std::cout << gcd_naive(a, b) << std::endl; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/3_greatest_common_divisor/gcd.hs: -------------------------------------------------------------------------------- 1 | -- by Kirill Elagin 2 | 3 | gcd_naive :: Int -> Int -> Int 4 | gcd_naive a b = maximum [ d | d <- [1 .. min a b], a `mod` d == 0 && b `mod` d == 0 ] 5 | 6 | main :: IO () 7 | main = do 8 | [a, b] <- fmap words getLine 9 | print $ gcd_naive (read a) (read b) 10 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/3_greatest_common_divisor/gcd.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | 5 | def gcd_naive(a, b): 6 | current_gcd = 1 7 | for d in range(2, min(a, b) + 1): 8 | if a % d == 0 and b % d == 0: 9 | if d > current_gcd: 10 | current_gcd = d 11 | 12 | return current_gcd 13 | 14 | 15 | def egcd(a, b): 16 | if b == 0: 17 | return a 18 | r = a % b 19 | return egcd(b, r) 20 | 21 | 22 | if __name__ == "__main__": 23 | input = sys.stdin.read() 24 | a, b = map(int, input.split()) 25 | print(egcd(a, b)) 26 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/4_least_common_multiple/LCM.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class LCM { 4 | private static long lcm_naive(int a, int b) { 5 | for (long l = 1; l <= (long) a * b; ++l) 6 | if (l % a == 0 && l % b == 0) 7 | return l; 8 | 9 | return (long) a * b; 10 | } 11 | 12 | public static void main(String args[]) { 13 | Scanner scanner = new Scanner(System.in); 14 | int a = scanner.nextInt(); 15 | int b = scanner.nextInt(); 16 | 17 | System.out.println(lcm_naive(a, b)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/4_least_common_multiple/LCM.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun lcmNaive(a: Int, b: Int): Long { 4 | for (l in 1..a.toLong() * b) 5 | if (l % a == 0L && l % b == 0L) 6 | return l 7 | 8 | return a.toLong() * b 9 | } 10 | 11 | fun main(args: Array) { 12 | val scanner = Scanner(System.`in`) 13 | val a = scanner.nextInt() 14 | val b = scanner.nextInt() 15 | 16 | println(lcmNaive(a, b)) 17 | } -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/4_least_common_multiple/by_learners/lcm.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def gcd(a, b) 5 | # fix me 6 | a * b 7 | end 8 | 9 | def lcm(a, b) 10 | # fix me 11 | a * b 12 | end 13 | 14 | if __FILE__ == $0 15 | a, b = gets.split().map(&:to_i) 16 | puts "#{lcm(a, b)}" 17 | end 18 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/4_least_common_multiple/lcm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | long long lcm_naive(int a, int b) { 4 | for (long l = 1; l <= (long long) a * b; ++l) 5 | if (l % a == 0 && l % b == 0) 6 | return l; 7 | 8 | return (long long) a * b; 9 | } 10 | 11 | int main() { 12 | int a, b; 13 | std::cin >> a >> b; 14 | std::cout << lcm_naive(a, b) << std::endl; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/4_least_common_multiple/lcm.hs: -------------------------------------------------------------------------------- 1 | -- by Kirill Elagin 2 | 3 | lcm_naive :: Int -> Int -> Integer 4 | lcm_naive a b = minimum [ l | l <- [1 .. a' * b'], l `mod` a' == 0 && l `mod` b' == 0 ] 5 | where 6 | a' = fromIntegral a :: Integer 7 | b' = fromIntegral b :: Integer 8 | 9 | main :: IO () 10 | main = do 11 | [a, b] <- fmap words getLine 12 | print $ lcm_naive (read a) (read b) 13 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/4_least_common_multiple/lcm.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | 5 | def egcd(a, b): 6 | while b: 7 | a, b = b, a % b 8 | return a 9 | 10 | 11 | def lcm(a, b): 12 | return (a * b) // egcd(a, b) 13 | 14 | 15 | def lcm_naive(a, b): 16 | for l in range(1, a * b + 1): 17 | if l % a == 0 and l % b == 0: 18 | return l 19 | 20 | return a * b 21 | 22 | 23 | if __name__ == "__main__": 24 | input = sys.stdin.read() 25 | a, b = map(int, input.split()) 26 | print(lcm(a, b)) 27 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/5_fibonacci_number_again/FibonacciHuge.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class FibonacciHuge { 4 | private static long getFibonacciHugeNaive(long n, long m) { 5 | if (n <= 1) 6 | return n; 7 | 8 | long previous = 0; 9 | long current = 1; 10 | 11 | for (long i = 0; i < n - 1; ++i) { 12 | long tmp_previous = previous; 13 | previous = current; 14 | current = tmp_previous + current; 15 | } 16 | 17 | return current % m; 18 | } 19 | 20 | public static void main(String[] args) { 21 | Scanner scanner = new Scanner(System.in); 22 | long n = scanner.nextLong(); 23 | long m = scanner.nextLong(); 24 | System.out.println(getFibonacciHugeNaive(n, m)); 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/5_fibonacci_number_again/FibonacciHuge.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun getFibonacciHugeNaive(n: Long, m: Long): Long { 4 | if (n <= 1) return n 5 | 6 | var previous: Long = 0 7 | var current: Long = 1 8 | 9 | for (i in 0 until n - 1) { 10 | val tmpPrevious = previous 11 | previous = current 12 | current += tmpPrevious 13 | } 14 | 15 | return current % m 16 | } 17 | 18 | fun main(args: Array) { 19 | val scanner = Scanner(System.`in`) 20 | val n = scanner.nextLong() 21 | val m = scanner.nextLong() 22 | println(getFibonacciHugeNaive(n, m)) 23 | } -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/5_fibonacci_number_again/by_learners/fibonacci_huge.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def fib_huge(n, m) 5 | # fix me 6 | 0 7 | end 8 | 9 | if __FILE__ == $0 10 | a, b = gets.split().map(&:to_i) 11 | puts "#{fib_huge(a, b)}" 12 | end -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/5_fibonacci_number_again/fibonacci_huge.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | long long get_fibonacci_huge_naive(long long n, long long m) { 4 | if (n <= 1) 5 | return n; 6 | 7 | long long previous = 0; 8 | long long current = 1; 9 | 10 | for (long long i = 0; i < n - 1; ++i) { 11 | long long tmp_previous = previous; 12 | previous = current; 13 | current = tmp_previous + current; 14 | } 15 | 16 | return current % m; 17 | } 18 | 19 | int main() { 20 | long long n, m; 21 | std::cin >> n >> m; 22 | std::cout << get_fibonacci_huge_naive(n, m) << '\n'; 23 | } 24 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/5_fibonacci_number_again/fibonacci_huge.hs: -------------------------------------------------------------------------------- 1 | -- by Kirill Elagin 2 | 3 | get_fibonacci_huge_naive :: Integer -> Int -> Int 4 | get_fibonacci_huge_naive n m = helper (0, 1) n 5 | where 6 | helper (a, _) 0 = a `mod` m 7 | helper (a, b) i = helper (b, a + b) (i - 1) 8 | 9 | main :: IO () 10 | main = do 11 | [n, m] <- fmap words getLine 12 | print $ get_fibonacci_huge_naive (read n) (read m) 13 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/5_fibonacci_number_again/fibonacci_huge.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | 5 | def get_fibonacci_huge_naive(n, m): 6 | if n <= 1: 7 | return n 8 | 9 | previous = 0 10 | current = 1 11 | 12 | for _ in range(n - 1): 13 | previous, current = current, previous + current 14 | 15 | return current % m 16 | 17 | 18 | def get_fibonacci_huge(n, m, return_arr=False): 19 | if n <= 1: 20 | return n 21 | 22 | arr = [0, 1] 23 | previous = 0 24 | current = 1 25 | 26 | for i in range(1, n): 27 | temp = previous 28 | previous = current % m 29 | current = (temp + current) % m 30 | arr.append(current) 31 | if current == 1 and previous == 0: 32 | index = n % i 33 | if return_arr: 34 | return arr 35 | return arr[index] 36 | 37 | if return_arr: 38 | return arr 39 | return current 40 | 41 | 42 | if __name__ == "__main__": 43 | input = sys.stdin.read() 44 | n, m = map(int, input.split()) 45 | print(get_fibonacci_huge(n, m)) 46 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/FibonacciSumLastDigit.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class FibonacciSumLastDigit { 4 | private static long getFibonacciSumNaive(long n) { 5 | if (n <= 1) 6 | return n; 7 | 8 | long previous = 0; 9 | long current = 1; 10 | long sum = 1; 11 | 12 | for (long i = 0; i < n - 1; ++i) { 13 | long tmp_previous = previous; 14 | previous = current; 15 | current = tmp_previous + current; 16 | sum += current; 17 | } 18 | 19 | return sum % 10; 20 | } 21 | 22 | public static void main(String[] args) { 23 | Scanner scanner = new Scanner(System.in); 24 | long n = scanner.nextLong(); 25 | long s = getFibonacciSumNaive(n); 26 | System.out.println(s); 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/FibonacciSumLastDigit.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun getFibonacciSumNaive(n: Long): Long { 4 | if (n <= 1) 5 | return n 6 | 7 | var previous: Long = 0 8 | var current: Long = 1 9 | var sum: Long = 1 10 | 11 | for (i in 0 until n - 1) { 12 | val tmpPrevious = previous 13 | previous = current 14 | current += tmpPrevious 15 | sum += current 16 | } 17 | 18 | return sum % 10 19 | } 20 | 21 | fun main(args: Array) { 22 | val scanner = Scanner(System.`in`) 23 | val n = scanner.nextLong() 24 | val s = getFibonacciSumNaive(n) 25 | println(s) 26 | } -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/by_learners/fibonacci_sum_last_digit.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def fib_sum_last_digit(n) 5 | # write your code here 6 | 0 7 | end 8 | 9 | if __FILE__ == $0 10 | n = gets.to_i 11 | puts "#{fib_sum_last_digit(n)}" 12 | end 13 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int fibonacci_sum_naive(long long n) { 4 | if (n <= 1) 5 | return n; 6 | 7 | long long previous = 0; 8 | long long current = 1; 9 | long long sum = 1; 10 | 11 | for (long long i = 0; i < n - 1; ++i) { 12 | long long tmp_previous = previous; 13 | previous = current; 14 | current = tmp_previous + current; 15 | sum += current; 16 | } 17 | 18 | return sum % 10; 19 | } 20 | 21 | int main() { 22 | long long n = 0; 23 | std::cin >> n; 24 | std::cout << fibonacci_sum_naive(n); 25 | } 26 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.hs: -------------------------------------------------------------------------------- 1 | -- by Kirill Elagin 2 | 3 | fibonacci_sum_naive :: Integer -> Int 4 | fibonacci_sum_naive = helper (0, 1, 0) 5 | where 6 | helper (_, _, s) 0 = s `mod` 10 7 | helper (a, b, s) i = helper (b, a + b, s + b) (i - 1) 8 | 9 | main :: IO () 10 | main = do 11 | [n] <- fmap words getLine 12 | print $ fibonacci_sum_naive (read n) 13 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | 5 | def fibonacci_sum_naive(n): 6 | if n <= 1: 7 | return n 8 | 9 | previous = 0 10 | current = 1 11 | sum = 1 12 | 13 | for _ in range(n - 1): 14 | previous, current = current, previous + current 15 | sum += current 16 | 17 | return sum % 10 18 | 19 | 20 | def fib(a): 21 | if n <= 1: 22 | return n 23 | previous = 0 24 | current = 1 25 | for i in range(2, a): 26 | previous, current = current, previous + current 27 | return current 28 | 29 | 30 | def fib_sum(n): 31 | if n <= 1: 32 | return n 33 | 34 | n = (n + 2) % 60 35 | fib = [0, 1] 36 | for i in range(2, n + 1): 37 | fib.append((fib[i - 1] % 10 + fib[i - 2] % 10) % 10) 38 | 39 | if fib[n] == 0: 40 | return 9 41 | return fib[n] % 10 - 1 42 | 43 | 44 | if __name__ == "__main__": 45 | input = sys.stdin.read() 46 | n = int(input) 47 | print(fib_sum(n)) 48 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/7_last_digit_of_the_sum_of_fibonacci_numbers_again/FibonacciPartialSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class FibonacciPartialSum { 4 | private static long getFibonacciPartialSumNaive(long from, long to) { 5 | long sum = 0; 6 | 7 | long current = 0; 8 | long next = 1; 9 | 10 | for (long i = 0; i <= to; ++i) { 11 | if (i >= from) { 12 | sum += current; 13 | } 14 | 15 | long new_current = next; 16 | next = next + current; 17 | current = new_current; 18 | } 19 | 20 | return sum % 10; 21 | } 22 | 23 | public static void main(String[] args) { 24 | Scanner scanner = new Scanner(System.in); 25 | long from = scanner.nextLong(); 26 | long to = scanner.nextLong(); 27 | System.out.println(getFibonacciPartialSumNaive(from, to)); 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/7_last_digit_of_the_sum_of_fibonacci_numbers_again/FibonacciPartialSum.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun getFibonacciPartialSumNaive(from: Long, to: Long): Long { 4 | var sum: Long = 0 5 | 6 | var current: Long = 0 7 | var next: Long = 1 8 | 9 | for (i in 0..to) { 10 | if (i >= from) { 11 | sum += current 12 | } 13 | 14 | val newCurrent = next 15 | next += current 16 | current = newCurrent 17 | } 18 | 19 | return sum % 10 20 | } 21 | 22 | fun main(args: Array) { 23 | val scanner = Scanner(System.`in`) 24 | val from = scanner.nextLong() 25 | val to = scanner.nextLong() 26 | println(getFibonacciPartialSumNaive(from, to)) 27 | } -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/7_last_digit_of_the_sum_of_fibonacci_numbers_again/by_learners/fib_partial_sum.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def fib_partial_sum(m, n) 5 | # write your code here 6 | 0 7 | end 8 | 9 | if __FILE__ == $0 10 | m, n = gets.split().map(&:to_i) 11 | puts "#{fib_partial_sum(m, n)}" 12 | end 13 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using std::vector; 4 | 5 | long long get_fibonacci_partial_sum_naive(long long from, long long to) { 6 | long long sum = 0; 7 | 8 | long long current = 0; 9 | long long next = 1; 10 | 11 | for (long long i = 0; i <= to; ++i) { 12 | if (i >= from) { 13 | sum += current; 14 | } 15 | 16 | long long new_current = next; 17 | next = next + current; 18 | current = new_current; 19 | } 20 | 21 | return sum % 10; 22 | } 23 | 24 | int main() { 25 | long long from, to; 26 | std::cin >> from >> to; 27 | std::cout << get_fibonacci_partial_sum_naive(from, to) << '\n'; 28 | } 29 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.hs: -------------------------------------------------------------------------------- 1 | -- by Kirill Elagin 2 | 3 | fibonacci_partial_sum_naive :: Integer -> Integer -> Int 4 | fibonacci_partial_sum_naive from to = let (a', b', _) = helper (0, 1, 0) from 5 | (_, _, s) = helper (a', b', a') (to - from) 6 | in s 7 | where 8 | helper (a, b, s) 0 = (a, b, s `mod` 10) 9 | helper (a, b, s) i = helper (b, a + b, s + b) (i - 1) 10 | 11 | main :: IO () 12 | main = do 13 | [from, to] <- fmap words getLine 14 | print $ fibonacci_partial_sum_naive (read from) (read to) 15 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | 5 | def fibonacci_partial_sum_naive(from_, to): 6 | sum = 0 7 | 8 | current = 0 9 | next = 1 10 | 11 | for i in range(to + 1): 12 | if i >= from_: 13 | sum += current 14 | 15 | current, next = next, current + next 16 | 17 | return sum % 10 18 | 19 | 20 | def partial_fib_sum(m, n): 21 | if m > n: 22 | return 23 | 24 | a = [0, 1] 25 | for i in range(2, 60): 26 | a.append(a[i - 1] + a[i - 2]) 27 | 28 | m = m % 60 29 | n = n % 60 30 | 31 | if n < m: 32 | n += 60 33 | 34 | sum_ = 0 35 | 36 | for j in range(m, n + 1): 37 | sum_ += a[j % 60] 38 | 39 | return sum_ % 10 40 | 41 | 42 | if __name__ == "__main__": 43 | input = sys.stdin.read() 44 | from_, to = map(int, input.split()) 45 | print(partial_fib_sum(from_, to)) 46 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers/FibonacciSumSquares.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class FibonacciSumSquares { 4 | private static long getFibonacciSumSquaresNaive(long n) { 5 | if (n <= 1) 6 | return n; 7 | 8 | long previous = 0; 9 | long current = 1; 10 | long sum = 1; 11 | 12 | for (long i = 0; i < n - 1; ++i) { 13 | long tmp_previous = previous; 14 | previous = current; 15 | current = tmp_previous + current; 16 | sum += current * current; 17 | } 18 | 19 | return sum % 10; 20 | } 21 | 22 | public static void main(String[] args) { 23 | Scanner scanner = new Scanner(System.in); 24 | long n = scanner.nextLong(); 25 | long s = getFibonacciSumSquaresNaive(n); 26 | System.out.println(s); 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers/fibonacci_sum_squares.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int fibonacci_sum_squares_naive(long long n) { 4 | if (n <= 1) 5 | return n; 6 | 7 | long long previous = 0; 8 | long long current = 1; 9 | long long sum = 1; 10 | 11 | for (long long i = 0; i < n - 1; ++i) { 12 | long long tmp_previous = previous; 13 | previous = current; 14 | current = tmp_previous + current; 15 | sum += current * current; 16 | } 17 | 18 | return sum % 10; 19 | } 20 | 21 | int main() { 22 | long long n = 0; 23 | std::cin >> n; 24 | std::cout << fibonacci_sum_squares_naive(n); 25 | } 26 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers/fibonacci_sum_squares.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | from sys import stdin 3 | 4 | 5 | def get_fib_last_digit(n): 6 | if n < 1: 7 | return n 8 | 9 | prev = 0 10 | curr = 1 11 | 12 | for _ in range(n - 1): 13 | prev, curr = curr % 10, (prev + curr) % 10 14 | return curr % 10 15 | 16 | 17 | def get_fib_sum_squares(n): 18 | vertical_side = get_fib_last_digit(n % 60) 19 | horizontal_side = get_fib_last_digit((n + 1) % 60) 20 | return (vertical_side * horizontal_side) % 10 21 | 22 | 23 | if __name__ == "__main__": 24 | n = int(stdin.read()) 25 | print(get_fib_sum_squares(n)) 26 | -------------------------------------------------------------------------------- /input/week2_algorithmic_warmup/week2_algorithmic_warmup.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WillKoehrsen/data-structures-and-algorithms-coursera/d13b5460447d3decc095aa54b883e01d8c8a9860/input/week2_algorithmic_warmup/week2_algorithmic_warmup.pdf -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WillKoehrsen/data-structures-and-algorithms-coursera/d13b5460447d3decc095aa54b883e01d8c8a9860/input/week3_greedy_algorithms/.DS_Store -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/1_money_change/Change.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Change { 4 | private static int getChange(int m) { 5 | //write your code here 6 | return m; 7 | } 8 | 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | int m = scanner.nextInt(); 12 | System.out.println(getChange(m)); 13 | 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/1_money_change/Change.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun getChange(m: Int): Int { 4 | //write your code here 5 | return m 6 | } 7 | 8 | fun main(args: Array) { 9 | val scanner = Scanner(System.`in`) 10 | val m = scanner.nextInt() 11 | println(getChange(m)) 12 | } -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/1_money_change/by_learners/change.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def get_change(n) 5 | count = 0 6 | coins = [1, 5, 10] 7 | # write your code here 8 | count 9 | end 10 | 11 | if __FILE__ == $0 12 | n = gets.to_i 13 | puts "#{get_change(n)}" 14 | end 15 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/1_money_change/change.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int get_change(int m) { 4 | //write your code here 5 | return n; 6 | } 7 | 8 | int main() { 9 | int m; 10 | std::cin >> m; 11 | std::cout << get_change(m) << '\n'; 12 | } 13 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/1_money_change/change.hs: -------------------------------------------------------------------------------- 1 | -- by Kirill Elagin 2 | 3 | get_change :: Int -> Int 4 | get_change m = n -- write your code here 5 | 6 | main :: IO () 7 | main = do 8 | [m] <- fmap words getLine 9 | print $ get_change (read m) 10 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/1_money_change/change.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | 5 | def get_change(m): 6 | tens = m // 10 7 | leftover = m % 10 8 | fives = leftover // 5 9 | return tens + fives + leftover % 5 10 | 11 | 12 | if __name__ == "__main__": 13 | m = int(sys.stdin.read()) 14 | print(get_change(m)) 15 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/2_maximum_value_of_the_loot/FractionalKnapsack.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class FractionalKnapsack { 4 | private static double getOptimalValue(int capacity, int[] values, int[] weights) { 5 | double value = 0; 6 | //write your code here 7 | 8 | return value; 9 | } 10 | 11 | public static void main(String args[]) { 12 | Scanner scanner = new Scanner(System.in); 13 | int n = scanner.nextInt(); 14 | int capacity = scanner.nextInt(); 15 | int[] values = new int[n]; 16 | int[] weights = new int[n]; 17 | for (int i = 0; i < n; i++) { 18 | values[i] = scanner.nextInt(); 19 | weights[i] = scanner.nextInt(); 20 | } 21 | System.out.println(getOptimalValue(capacity, values, weights)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/2_maximum_value_of_the_loot/FractionalKnapsack.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun getOptimalValue(capacity: Int, values: IntArray, weights: IntArray): Double { 4 | //write your code here 5 | return 0.0 6 | } 7 | 8 | fun main(args: Array) { 9 | val scanner = Scanner(System.`in`) 10 | val n = scanner.nextInt() 11 | val capacity = scanner.nextInt() 12 | val values = IntArray(n) 13 | val weights = IntArray(n) 14 | for (i in 0 until n) { 15 | values[i] = scanner.nextInt() 16 | weights[i] = scanner.nextInt() 17 | } 18 | println(getOptimalValue(capacity, values, weights)) 19 | } -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/2_maximum_value_of_the_loot/by_learners/fractional_knapsack.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def get_optimal_value(capacity, weights, values) 5 | value = 0.0 6 | # write your code here 7 | value 8 | end 9 | 10 | if __FILE__ == $0 11 | data = STDIN.read.split().map(&:to_i) 12 | n, capacity = data[0,2] 13 | values = data.values_at(*(2..2*n).step(2)) 14 | weights = data.values_at(*(3..2*n+1).step(2)) 15 | 16 | answer = get_optimal_value(capacity, weights, values) 17 | puts "#{'%.4f' % answer}" 18 | end -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/2_maximum_value_of_the_loot/fractional_knapsack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::vector; 5 | 6 | double get_optimal_value(int capacity, vector weights, vector values) { 7 | double value = 0.0; 8 | 9 | // write your code here 10 | 11 | return value; 12 | } 13 | 14 | int main() { 15 | int n; 16 | int capacity; 17 | std::cin >> n >> capacity; 18 | vector values(n); 19 | vector weights(n); 20 | for (int i = 0; i < n; i++) { 21 | std::cin >> values[i] >> weights[i]; 22 | } 23 | 24 | double optimal_value = get_optimal_value(capacity, weights, values); 25 | 26 | std::cout.precision(10); 27 | std::cout << optimal_value << std::endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/2_maximum_value_of_the_loot/fractional_knapsack.hs: -------------------------------------------------------------------------------- 1 | -- by Kirill Elagin 2 | 3 | import Control.Monad (replicateM) 4 | import Numeric (showFFloat) 5 | 6 | 7 | type Item = (Int, Int) 8 | 9 | get_optimal_value :: Int -> [Item] -> Double 10 | get_optimal_value capacity items = value -- write your code here 11 | 12 | main :: IO () 13 | main = do 14 | [n', capacity'] <- fmap words getLine 15 | let (n, capacity) = (read n', read capacity') 16 | items <- replicateM n $ fmap ((\[v, w] -> (read v, read w)) . words) getLine 17 | printFloat $ get_optimal_value capacity items 18 | where 19 | printFloat x = putStrLn $ showFFloat (Just 4) x "" 20 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/2_maximum_value_of_the_loot/fractional_knapsack.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | 5 | def get_optimal_value(capacity, weights, values): 6 | value = 0. 7 | # write your code here 8 | unit_values = [v / w for w, v in zip(weights, values)] 9 | tup_values = [(u, w, v) for u, w, v in zip(unit_values, weights, values)] 10 | total_weight = 0 11 | while total_weight < capacity: 12 | if not tup_values: 13 | break 14 | available_weight = capacity - total_weight 15 | max_unit_value, max_weight, max_value = max(tup_values) 16 | if max_weight <= available_weight: 17 | total_weight += max_weight 18 | value += max_value 19 | else: 20 | total_weight += available_weight 21 | value += max_unit_value * available_weight 22 | tup_values.remove((max_unit_value, max_weight, max_value)) 23 | return value 24 | 25 | 26 | if __name__ == "__main__": 27 | data = list(map(int, sys.stdin.read().split())) 28 | n, capacity = data[0:2] 29 | values = data[2 : (2 * n + 2) : 2] 30 | weights = data[3 : (2 * n + 2) : 2] 31 | opt_value = get_optimal_value(capacity, weights, values) 32 | print("{:.10f}".format(opt_value)) 33 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/3_car_fueling/CarFueling.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class CarFueling { 5 | static int computeMinRefills(int dist, int tank, int[] stops) { 6 | return -1; 7 | } 8 | 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | int dist = scanner.nextInt(); 12 | int tank = scanner.nextInt(); 13 | int n = scanner.nextInt(); 14 | int stops[] = new int[n]; 15 | for (int i = 0; i < n; i++) { 16 | stops[i] = scanner.nextInt(); 17 | } 18 | 19 | System.out.println(computeMinRefills(dist, tank, stops)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/3_car_fueling/car_fueling.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cin; 5 | using std::cout; 6 | using std::vector; 7 | using std::max; 8 | 9 | int compute_min_refills(int dist, int tank, vector & stops) { 10 | // write your code here 11 | return -1; 12 | } 13 | 14 | 15 | int main() { 16 | int d = 0; 17 | cin >> d; 18 | int m = 0; 19 | cin >> m; 20 | int n = 0; 21 | cin >> n; 22 | 23 | vector stops(n); 24 | for (size_t i = 0; i < n; ++i) 25 | cin >> stops.at(i); 26 | 27 | cout << compute_min_refills(d, m, stops) << "\n"; 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/3_car_fueling/car_fueling.py: -------------------------------------------------------------------------------- 1 | # python3 2 | import sys 3 | 4 | 5 | def compute_min_refills(distance, tank, stops): 6 | current_position = 0 7 | fillups = 0 8 | new_stops = stops[:] 9 | while (current_position + tank) < distance: 10 | fillups += 1 11 | diffs = [stop for stop in new_stops if (stop - current_position) <= tank] 12 | if not diffs: 13 | return -1 14 | next_stop = max(diffs) 15 | current_position = next_stop 16 | new_stops.remove(next_stop) 17 | 18 | # write your code here 19 | return fillups 20 | 21 | 22 | if __name__ == "__main__": 23 | d, m, _, *stops = map(int, sys.stdin.read().split()) 24 | print(compute_min_refills(d, m, stops)) 25 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/4_maximum_advertisement_revenue/DotProduct.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class DotProduct { 4 | private static long maxDotProduct(int[] a, int[] b) { 5 | //write your code here 6 | long result = 0; 7 | for (int i = 0; i < a.length; i++) { 8 | result += a[i] * b[i]; 9 | } 10 | return result; 11 | } 12 | 13 | public static void main(String[] args) { 14 | Scanner scanner = new Scanner(System.in); 15 | int n = scanner.nextInt(); 16 | int[] a = new int[n]; 17 | for (int i = 0; i < n; i++) { 18 | a[i] = scanner.nextInt(); 19 | } 20 | int[] b = new int[n]; 21 | for (int i = 0; i < n; i++) { 22 | b[i] = scanner.nextInt(); 23 | } 24 | System.out.println(maxDotProduct(a, b)); 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/4_maximum_advertisement_revenue/DotProduct.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun maxDotProduct(a: IntArray, b: IntArray): Long { 4 | //write your code here 5 | var result: Long = 0 6 | for (i in a.indices) { 7 | result += (a[i] * b[i]).toLong() 8 | } 9 | return result 10 | } 11 | 12 | fun main(args: Array) { 13 | val scanner = Scanner(System.`in`) 14 | val n = scanner.nextInt() 15 | val a = IntArray(n) 16 | for (i in 0 until n) { 17 | a[i] = scanner.nextInt() 18 | } 19 | val b = IntArray(n) 20 | for (i in 0 until n) { 21 | b[i] = scanner.nextInt() 22 | } 23 | println(maxDotProduct(a, b)) 24 | } -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/4_maximum_advertisement_revenue/by_learners/dot_rpoduct.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def max_dot_product(a, b) 5 | #write your code here 6 | end 7 | 8 | if __FILE__ == $0 9 | data = STDIN.read.split().map(&:to_i) 10 | n = data[0] 11 | a, b = data[1..n], data[n+1..2*n] 12 | puts "#{min_dot_product(a, b)}" 13 | end -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/4_maximum_advertisement_revenue/dot_product.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using std::vector; 6 | 7 | long long max_dot_product(vector a, vector b) { 8 | // write your code here 9 | long long result = 0; 10 | for (size_t i = 0; i < a.size(); i++) { 11 | result += ((long long) a[i]) * b[i]; 12 | } 13 | return result; 14 | } 15 | 16 | int main() { 17 | size_t n; 18 | std::cin >> n; 19 | vector a(n), b(n); 20 | for (size_t i = 0; i < n; i++) { 21 | std::cin >> a[i]; 22 | } 23 | for (size_t i = 0; i < n; i++) { 24 | std::cin >> b[i]; 25 | } 26 | std::cout << max_dot_product(a, b) << std::endl; 27 | } 28 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/4_maximum_advertisement_revenue/dot_product.hs: -------------------------------------------------------------------------------- 1 | -- by Kirill Elagin 2 | 3 | max_dot_product :: [Int] -> [Int] -> Integer 4 | max_dot_product as bs = result -- write your code here 5 | 6 | main :: IO () 7 | main = do 8 | _ <- getLine 9 | as <- fmap (map read . words) getLine 10 | bs <- fmap (map read . words) getLine 11 | print $ max_dot_product as bs 12 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/4_maximum_advertisement_revenue/dot_product.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | 3 | import sys 4 | 5 | 6 | def max_dot_product(a, b): 7 | # write your code here 8 | res = 0 9 | a = sorted(a, reverse=True) 10 | for elem_a in a: 11 | max_prod = float("-inf") 12 | for elem_b in b: 13 | prod = elem_a * elem_b 14 | if prod > max_prod: 15 | largest_b = elem_b 16 | max_prod = prod 17 | res += max_prod 18 | b.remove(largest_b) 19 | return res 20 | 21 | 22 | if __name__ == "__main__": 23 | input = sys.stdin.read() 24 | data = list(map(int, input.split())) 25 | n = data[0] 26 | a = data[1 : (n + 1)] 27 | b = data[(n + 1) :] 28 | print(max_dot_product(a, b)) 29 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/5_collecting_signatures/CoveringSegments.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class CoveringSegments { 4 | 5 | private static int[] optimalPoints(Segment[] segments) { 6 | //write your code here 7 | int[] points = new int[2 * segments.length]; 8 | for (int i = 0; i < segments.length; i++) { 9 | points[2 * i] = segments[i].start; 10 | points[2 * i + 1] = segments[i].end; 11 | } 12 | return points; 13 | } 14 | 15 | private static class Segment { 16 | int start, end; 17 | 18 | Segment(int start, int end) { 19 | this.start = start; 20 | this.end = end; 21 | } 22 | } 23 | public static void main(String[] args) { 24 | Scanner scanner = new Scanner(System.in); 25 | int n = scanner.nextInt(); 26 | Segment[] segments = new Segment[n]; 27 | for (int i = 0; i < n; i++) { 28 | int start, end; 29 | start = scanner.nextInt(); 30 | end = scanner.nextInt(); 31 | segments[i] = new Segment(start, end); 32 | } 33 | int[] points = optimalPoints(segments); 34 | System.out.println(points.length); 35 | for (int point : points) { 36 | System.out.print(point + " "); 37 | } 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/5_collecting_signatures/CoveringSegments.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun optimalPoints(segments: MutableList): IntArray { 4 | //write your code here 5 | val points = IntArray(2 * segments.size) 6 | for (i in segments.indices) { 7 | points[2 * i] = segments[i].start 8 | points[2 * i + 1] = segments[i].end 9 | } 10 | return points 11 | } 12 | 13 | class Segment(var start: Int, var end: Int) 14 | 15 | fun main(args: Array) { 16 | val scanner = Scanner(System.`in`) 17 | val n = scanner.nextInt() 18 | val segments = ArrayList(n) 19 | repeat (n) { 20 | val start: Int = scanner.nextInt() 21 | val end: Int = scanner.nextInt() 22 | segments += Segment(start, end) 23 | } 24 | val points = optimalPoints(segments) 25 | println(points.size) 26 | for (point in points) { 27 | print(point.toString() + " ") 28 | } 29 | } -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/5_collecting_signatures/by_learners/covering_segments.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | Segment = Struct.new("Segment", :start, :end) 5 | 6 | def optimal_points(segments) 7 | points = [] 8 | return points if segments.empty? 9 | #write your code here 10 | points 11 | end 12 | 13 | if __FILE__ == $0 14 | data = STDIN.read.split().map(&:to_i) 15 | n = data[0] 16 | segments = data[1..2*n].each_slice(2).to_a.map { |e| Segment.new(e[0], e[1]) } 17 | points = optimal_points(segments) 18 | puts "#{points.size}" 19 | puts "#{points.join(' ')}" 20 | end -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/5_collecting_signatures/covering_segments.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using std::vector; 7 | 8 | struct Segment { 9 | int start, end; 10 | }; 11 | 12 | vector optimal_points(vector &segments) { 13 | vector points; 14 | //write your code here 15 | for (size_t i = 0; i < segments.size(); ++i) { 16 | points.push_back(segments[i].start); 17 | points.push_back(segments[i].end); 18 | } 19 | return points; 20 | } 21 | 22 | int main() { 23 | int n; 24 | std::cin >> n; 25 | vector segments(n); 26 | for (size_t i = 0; i < segments.size(); ++i) { 27 | std::cin >> segments[i].start >> segments[i].end; 28 | } 29 | vector points = optimal_points(segments); 30 | std::cout << points.size() << "\n"; 31 | for (size_t i = 0; i < points.size(); ++i) { 32 | std::cout << points[i] << " "; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/5_collecting_signatures/covering_segments.hs: -------------------------------------------------------------------------------- 1 | -- by Kirill Elagin 2 | 3 | import Control.Monad (replicateM) 4 | 5 | 6 | optimal_points :: [(Int, Int)] -> [Int] 7 | optimal_points segments = map fst segments -- write your code here 8 | 9 | main :: IO () 10 | main = do 11 | n' <- getLine 12 | let n = read n' 13 | segments <- replicateM n $ fmap ((\[s, e] -> (read s, read e)) . words) getLine 14 | let points = optimal_points segments 15 | print $ length points 16 | putStrLn $ unwords (map show points) 17 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/5_collecting_signatures/covering_segments.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | from collections import namedtuple 4 | from copy import deepcopy 5 | 6 | # Segments have a start and end 7 | Segment = namedtuple("Segment", "start end") 8 | 9 | 10 | def optimal_points(segments): 11 | points = [] 12 | # Sort by the smallest end ascending 13 | segments = sorted(segments, key=lambda x: x.end) 14 | point = segments[0].end 15 | points.append(point) 16 | 17 | for i in range(1, len(segments)): 18 | # If segment is not covered 19 | if point < segments[i].start or point > segments[i].end: 20 | # Add the ending point of the segment 21 | point = segments[i].end 22 | points.append(point) 23 | return points 24 | 25 | 26 | if __name__ == "__main__": 27 | input = sys.stdin.read() 28 | n, *data = map(int, input.split()) 29 | segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2]))) 30 | points = optimal_points(segments) 31 | print(len(points)) 32 | for p in points: 33 | print(p, end=" ") 34 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/6_maximum_number_of_prizes/DifferentSummands.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class DifferentSummands { 4 | private static List optimalSummands(int n) { 5 | List summands = new ArrayList(); 6 | //write your code here 7 | return summands; 8 | } 9 | 10 | public static void main(String[] args) { 11 | Scanner scanner = new Scanner(System.in); 12 | int n = scanner.nextInt(); 13 | List summands = optimalSummands(n); 14 | System.out.println(summands.size()); 15 | for (Integer summand : summands) { 16 | System.out.print(summand + " "); 17 | } 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/6_maximum_number_of_prizes/DifferentSummands.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun optimalSummands(n: Int): List { 4 | //write your code here 5 | return ArrayList() 6 | } 7 | 8 | fun main(args: Array) { 9 | val scanner = Scanner(System.`in`) 10 | val n = scanner.nextInt() 11 | val summands = optimalSummands(n) 12 | println(summands.size) 13 | for (summand in summands) { 14 | print(summand.toString() + " ") 15 | } 16 | } -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/6_maximum_number_of_prizes/by_learners/different_summands.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def optimal_summands(n) 5 | summands = [] 6 | #write your code here 7 | summands 8 | end 9 | 10 | if __FILE__ == $0 11 | n = gets.to_i 12 | summands = optimal_summands(n) 13 | puts "#{summands.size}" 14 | puts "#{summands.join(' ')}" 15 | end -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/6_maximum_number_of_prizes/different_summands.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::vector; 5 | 6 | vector optimal_summands(int n) { 7 | vector summands; 8 | //write your code here 9 | return summands; 10 | } 11 | 12 | int main() { 13 | int n; 14 | std::cin >> n; 15 | vector summands = optimal_summands(n); 16 | std::cout << summands.size() << '\n'; 17 | for (size_t i = 0; i < summands.size(); ++i) { 18 | std::cout << summands[i] << ' '; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/6_maximum_number_of_prizes/different_summands.hs: -------------------------------------------------------------------------------- 1 | -- by Kirill Elagin 2 | 3 | optimal_summands :: Int -> [Int] 4 | optimal_summands n = [n] -- write your code here 5 | 6 | main :: IO () 7 | main = do 8 | n <- getLine 9 | let summands = optimal_summands (read n) 10 | print $ length summands 11 | putStrLn $ unwords (map show summands) 12 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/6_maximum_number_of_prizes/different_summands.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | 5 | def optimal_summands(n): 6 | if n == 1: 7 | return [1] 8 | summands = [] 9 | # Amount still to allocate 10 | remainder = n 11 | 12 | for i in range(1, n): 13 | # Add next number if we can 14 | if remainder >= 2 * i + 1: 15 | summands.append(i) 16 | remainder -= i 17 | # Otherwise add leftover value and return 18 | else: 19 | summands.append(remainder) 20 | return summands 21 | 22 | return summands 23 | 24 | 25 | if __name__ == "__main__": 26 | input = sys.stdin.read() 27 | n = int(input) 28 | summands = optimal_summands(n) 29 | print(len(summands)) 30 | for x in summands: 31 | print(x, end=" ") 32 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/7_maximum_salary/LargestNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class LargestNumber { 4 | private static String largestNumber(String[] a) { 5 | //write your code here 6 | String result = ""; 7 | for (int i = 0; i < a.length; i++) { 8 | result += a[i]; 9 | } 10 | return result; 11 | } 12 | 13 | public static void main(String[] args) { 14 | Scanner scanner = new Scanner(System.in); 15 | int n = scanner.nextInt(); 16 | String[] a = new String[n]; 17 | for (int i = 0; i < n; i++) { 18 | a[i] = scanner.next(); 19 | } 20 | System.out.println(largestNumber(a)); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/7_maximum_salary/LargestNumber.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun largestNumber(a: MutableList): String { 4 | //write your code here 5 | return a.joinToString("") 6 | } 7 | 8 | fun main(args: Array) { 9 | val scanner = Scanner(System.`in`) 10 | val n = scanner.nextInt() 11 | val a = ArrayList(n) 12 | repeat(n) { 13 | a += scanner.next() 14 | } 15 | println(largestNumber(a)) 16 | } -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/7_maximum_salary/by_learners/largest_number.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def largest_number(a) 5 | # write your code here 6 | a.join('') 7 | end 8 | 9 | if __FILE__ == $0 10 | a = STDIN.read.split().drop(1) 11 | puts largest_number(a) 12 | end -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/7_maximum_salary/largest_number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using std::vector; 8 | using std::string; 9 | 10 | string largest_number(vector a) { 11 | //write your code here 12 | std::stringstream ret; 13 | for (size_t i = 0; i < a.size(); i++) { 14 | ret << a[i]; 15 | } 16 | string result; 17 | ret >> result; 18 | return result; 19 | } 20 | 21 | int main() { 22 | int n; 23 | std::cin >> n; 24 | vector a(n); 25 | for (size_t i = 0; i < a.size(); i++) { 26 | std::cin >> a[i]; 27 | } 28 | std::cout << largest_number(a); 29 | } 30 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/7_maximum_salary/largest_number.hs: -------------------------------------------------------------------------------- 1 | -- by Kirill Elagin 2 | 3 | largest_number :: [Int] -> String 4 | largest_number as = concat (map show as) -- write your code here 5 | 6 | main :: IO () 7 | main = do 8 | _ <- getLine 9 | as <- fmap (map read . words) getLine 10 | putStrLn $ largest_number as 11 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/7_maximum_salary/largest_number.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | 3 | import sys 4 | 5 | 6 | def is_greater_equal(a, b): 7 | if b == float("-inf"): 8 | return True 9 | # Direct comparison of order 10 | if "".join([str(a), str(b)]) >= "".join([str(b), str(a)]): 11 | return True 12 | return False 13 | 14 | 15 | def largest_number(a): 16 | ans = [] 17 | 18 | while a: 19 | max_digit = float("-inf") 20 | # Iterate through each remaining digit 21 | for digit in a: 22 | # Add if this digit results in a greater number 23 | if is_greater_equal(digit, max_digit): 24 | max_digit = digit 25 | # Add to answer and remove from list of digits 26 | ans.append(max_digit) 27 | a.remove(max_digit) 28 | 29 | return int("".join(ans)) 30 | 31 | 32 | if __name__ == "__main__": 33 | input = sys.stdin.read() 34 | data = input.split() 35 | a = data[1:] 36 | print(largest_number(a)) 37 | -------------------------------------------------------------------------------- /input/week3_greedy_algorithms/week3_greedy_algorithms.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WillKoehrsen/data-structures-and-algorithms-coursera/d13b5460447d3decc095aa54b883e01d8c8a9860/input/week3_greedy_algorithms/week3_greedy_algorithms.pdf -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/1_binary_search/BinarySearch.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class BinarySearch { 5 | 6 | static int binarySearch(int[] a, int x) { 7 | int left = 0, right = a.length; 8 | //write your code here 9 | 10 | return -1; 11 | } 12 | 13 | static int linearSearch(int[] a, int x) { 14 | for (int i = 0; i < a.length; i++) { 15 | if (a[i] == x) return i; 16 | } 17 | return -1; 18 | } 19 | 20 | public static void main(String[] args) { 21 | FastScanner scanner = new FastScanner(System.in); 22 | int n = scanner.nextInt(); 23 | int[] a = new int[n]; 24 | for (int i = 0; i < n; i++) { 25 | a[i] = scanner.nextInt(); 26 | } 27 | int m = scanner.nextInt(); 28 | int[] b = new int[m]; 29 | for (int i = 0; i < m; i++) { 30 | b[i] = scanner.nextInt(); 31 | } 32 | for (int i = 0; i < m; i++) { 33 | //replace with the call to binarySearch when implemented 34 | System.out.print(linearSearch(a, b[i]) + " "); 35 | } 36 | } 37 | static class FastScanner { 38 | BufferedReader br; 39 | StringTokenizer st; 40 | 41 | FastScanner(InputStream stream) { 42 | try { 43 | br = new BufferedReader(new InputStreamReader(stream)); 44 | } catch (Exception e) { 45 | e.printStackTrace(); 46 | } 47 | } 48 | 49 | String next() { 50 | while (st == null || !st.hasMoreTokens()) { 51 | try { 52 | st = new StringTokenizer(br.readLine()); 53 | } catch (IOException e) { 54 | e.printStackTrace(); 55 | } 56 | } 57 | return st.nextToken(); 58 | } 59 | 60 | int nextInt() { 61 | return Integer.parseInt(next()); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/1_binary_search/BinarySearch.kt: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader 2 | import java.io.IOException 3 | import java.io.InputStream 4 | import java.io.InputStreamReader 5 | import java.util.* 6 | 7 | fun binarySearch(a: IntArray, x: Int): Int { 8 | val left = 0 9 | val right = a.size 10 | //write your code here 11 | 12 | return -1 13 | } 14 | 15 | fun linearSearch(a: IntArray, x: Int): Int { 16 | for (i in a.indices) { 17 | if (a[i] == x) return i 18 | } 19 | return -1 20 | } 21 | 22 | fun main(args: Array) { 23 | val scanner = FastScanner(System.`in`) 24 | val n = scanner.nextInt() 25 | val a = IntArray(n) 26 | for (i in 0 until n) { 27 | a[i] = scanner.nextInt() 28 | } 29 | val m = scanner.nextInt() 30 | val b = IntArray(m) 31 | for (i in 0 until m) { 32 | b[i] = scanner.nextInt() 33 | } 34 | for (i in 0 until m) { 35 | //replace with the call to binarySearch when implemented 36 | print(linearSearch(a, b[i]).toString() + " ") 37 | } 38 | } 39 | 40 | class FastScanner(stream: InputStream) { 41 | var br: BufferedReader = BufferedReader(InputStreamReader(stream)) 42 | var st: StringTokenizer? = null 43 | 44 | fun next(): String { 45 | while (st == null || !st!!.hasMoreTokens()) { 46 | try { 47 | st = StringTokenizer(br.readLine()) 48 | } catch (e: IOException) { 49 | e.printStackTrace() 50 | } 51 | } 52 | return st!!.nextToken() 53 | } 54 | 55 | fun nextInt() = next().toInt() 56 | } -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/1_binary_search/binary_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using std::vector; 6 | 7 | int binary_search(const vector &a, int x) { 8 | int left = 0, right = (int)a.size(); 9 | //write your code here 10 | } 11 | 12 | int linear_search(const vector &a, int x) { 13 | for (size_t i = 0; i < a.size(); ++i) { 14 | if (a[i] == x) return i; 15 | } 16 | return -1; 17 | } 18 | 19 | int main() { 20 | int n; 21 | std::cin >> n; 22 | vector a(n); 23 | for (size_t i = 0; i < a.size(); i++) { 24 | std::cin >> a[i]; 25 | } 26 | int m; 27 | std::cin >> m; 28 | vector b(m); 29 | for (int i = 0; i < m; ++i) { 30 | std::cin >> b[i]; 31 | } 32 | for (int i = 0; i < m; ++i) { 33 | //replace with the call to binary_search when implemented 34 | std::cout << linear_search(a, b[i]) << ' '; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/1_binary_search/binary_search.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | 5 | def binary_search(a, x, left=None, right=None): 6 | if left is None: 7 | left = 0 8 | if right is None: 9 | right = len(a) - 1 10 | 11 | while right >= left: 12 | mid_index = int(left + (right - left) / 2) 13 | mid_value = a[mid_index] 14 | 15 | if x == mid_value: 16 | return mid_index 17 | elif x > mid_value: 18 | left = mid_index + 1 19 | elif x < mid_value: 20 | right = mid_index - 1 21 | return -1 22 | 23 | 24 | def linear_search(a, x): 25 | for i in range(len(a)): 26 | if a[i] == x: 27 | return i 28 | return -1 29 | 30 | 31 | if __name__ == "__main__": 32 | input = sys.stdin.read() 33 | data = list(map(int, input.split())) 34 | n = data[0] 35 | m = data[n + 1] 36 | a = data[1 : n + 1] 37 | for x in data[n + 2 :]: 38 | # replace with the call to binary_search when implemented 39 | print(binary_search(a, x), end=" ") 40 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/1_binary_search/by_learners/binary_search.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def binary_search(x, a) 5 | #write your code here 6 | -1 7 | end 8 | 9 | if __FILE__ == $0 10 | data = STDIN.read.split().map(&:to_i) 11 | n = data[0] 12 | a = data[1..n] 13 | m = data[n+1] 14 | data[n+2, m].each { |b| print("#{binary_search(b, a)} ") } 15 | puts "" 16 | end 17 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/2_majority_element/MajorityElement.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class MajorityElement { 5 | private static int getMajorityElement(int[] a, int left, int right) { 6 | if (left == right) { 7 | return -1; 8 | } 9 | if (left + 1 == right) { 10 | return a[left]; 11 | } 12 | //write your code here 13 | return -1; 14 | } 15 | 16 | public static void main(String[] args) { 17 | FastScanner scanner = new FastScanner(System.in); 18 | int n = scanner.nextInt(); 19 | int[] a = new int[n]; 20 | for (int i = 0; i < n; i++) { 21 | a[i] = scanner.nextInt(); 22 | } 23 | if (getMajorityElement(a, 0, a.length) != -1) { 24 | System.out.println(1); 25 | } else { 26 | System.out.println(0); 27 | } 28 | } 29 | static class FastScanner { 30 | BufferedReader br; 31 | StringTokenizer st; 32 | 33 | FastScanner(InputStream stream) { 34 | try { 35 | br = new BufferedReader(new InputStreamReader(stream)); 36 | } catch (Exception e) { 37 | e.printStackTrace(); 38 | } 39 | } 40 | 41 | String next() { 42 | while (st == null || !st.hasMoreTokens()) { 43 | try { 44 | st = new StringTokenizer(br.readLine()); 45 | } catch (IOException e) { 46 | e.printStackTrace(); 47 | } 48 | } 49 | return st.nextToken(); 50 | } 51 | 52 | int nextInt() { 53 | return Integer.parseInt(next()); 54 | } 55 | } 56 | } 57 | 58 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/2_majority_element/MajorityElement.kt: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader 2 | import java.io.IOException 3 | import java.io.InputStream 4 | import java.io.InputStreamReader 5 | import java.util.* 6 | 7 | fun getMajorityElement(a: IntArray, left: Int, right: Int): Int { 8 | if (left == right) return -1 9 | if (left + 1 == right) return a[left] 10 | //write your code here 11 | return -1 12 | } 13 | 14 | fun main(args: Array) { 15 | val scanner = FastScanner(System.`in`) 16 | val n = scanner.nextInt() 17 | val a = IntArray(n) 18 | for (i in 0 until n) { 19 | a[i] = scanner.nextInt() 20 | } 21 | if (getMajorityElement(a, 0, a.size) != -1) { 22 | println(1) 23 | } else { 24 | println(0) 25 | } 26 | } 27 | 28 | class FastScanner(stream: InputStream) { 29 | var br: BufferedReader = BufferedReader(InputStreamReader(stream)) 30 | var st: StringTokenizer? = null 31 | 32 | fun next(): String { 33 | while (st == null || !st!!.hasMoreTokens()) { 34 | try { 35 | st = StringTokenizer(br.readLine()) 36 | } catch (e: IOException) { 37 | e.printStackTrace() 38 | } 39 | } 40 | return st!!.nextToken() 41 | } 42 | 43 | fun nextInt() = next().toInt() 44 | } -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/2_majority_element/by_learners/majority_element.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def get_majority_element(a, left, right) 5 | return -1 if left >= right 6 | return a[left] if right - left == 1 7 | 8 | # write your code here 9 | -1 10 | end 11 | 12 | if __FILE__ == $0 13 | n, *a = STDIN.read.split().map(&:to_i) 14 | answer = get_majority_element(a, 0, n) != -1 15 | puts "#{answer ? 1 : 0}" 16 | end 17 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/2_majority_element/majority_element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using std::vector; 6 | 7 | int get_majority_element(vector &a, int left, int right) { 8 | if (left == right) return -1; 9 | if (left + 1 == right) return a[left]; 10 | //write your code here 11 | return -1; 12 | } 13 | 14 | int main() { 15 | int n; 16 | std::cin >> n; 17 | vector a(n); 18 | for (size_t i = 0; i < a.size(); ++i) { 19 | std::cin >> a[i]; 20 | } 21 | std::cout << (get_majority_element(a, 0, a.size()) != -1) << '\n'; 22 | } 23 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/2_majority_element/majority_element.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | from collections import Counter 4 | 5 | 6 | def get_majority_element(a, left=None, right=None): 7 | n = len(a) 8 | if n == 1: 9 | return a[0] 10 | k = n // 2 11 | 12 | elem_lsub = get_majority_element(a[:k]) 13 | elem_rsub = get_majority_element(a[k:]) 14 | if elem_lsub == elem_rsub: 15 | return elem_lsub 16 | 17 | lcount = a.count(elem_lsub) 18 | rcount = a.count(elem_rsub) 19 | if lcount > n / 2: 20 | return elem_lsub 21 | elif rcount > n / 2: 22 | return elem_rsub 23 | 24 | return -1 25 | 26 | 27 | if __name__ == "__main__": 28 | input = sys.stdin.read() 29 | n, *a = list(map(int, input.split())) 30 | if get_majority_element(a, 0, n) != -1: 31 | print(1) 32 | else: 33 | print(0) 34 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/3_improving_quicksort/Sorting.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Sorting { 5 | private static Random random = new Random(); 6 | 7 | private static int[] partition3(int[] a, int l, int r) { 8 | //write your code here 9 | 10 | 11 | int m1 = l; 12 | int m2 = r; 13 | int[] m = {m1, m2}; 14 | return m; 15 | } 16 | 17 | private static int partition2(int[] a, int l, int r) { 18 | int x = a[l]; 19 | int j = l; 20 | for (int i = l + 1; i <= r; i++) { 21 | if (a[i] <= x) { 22 | j++; 23 | int t = a[i]; 24 | a[i] = a[j]; 25 | a[j] = t; 26 | } 27 | } 28 | int t = a[l]; 29 | a[l] = a[j]; 30 | a[j] = t; 31 | return j; 32 | } 33 | 34 | private static void randomizedQuickSort(int[] a, int l, int r) { 35 | if (l >= r) { 36 | return; 37 | } 38 | int k = random.nextInt(r - l + 1) + l; 39 | int t = a[l]; 40 | a[l] = a[k]; 41 | a[k] = t; 42 | //use partition3 43 | int m = partition2(a, l, r); 44 | randomizedQuickSort(a, l, m - 1); 45 | randomizedQuickSort(a, m + 1, r); 46 | } 47 | 48 | public static void main(String[] args) { 49 | FastScanner scanner = new FastScanner(System.in); 50 | int n = scanner.nextInt(); 51 | int[] a = new int[n]; 52 | for (int i = 0; i < n; i++) { 53 | a[i] = scanner.nextInt(); 54 | } 55 | randomizedQuickSort(a, 0, n - 1); 56 | for (int i = 0; i < n; i++) { 57 | System.out.print(a[i] + " "); 58 | } 59 | } 60 | 61 | static class FastScanner { 62 | BufferedReader br; 63 | StringTokenizer st; 64 | 65 | FastScanner(InputStream stream) { 66 | try { 67 | br = new BufferedReader(new InputStreamReader(stream)); 68 | } catch (Exception e) { 69 | e.printStackTrace(); 70 | } 71 | } 72 | 73 | String next() { 74 | while (st == null || !st.hasMoreTokens()) { 75 | try { 76 | st = new StringTokenizer(br.readLine()); 77 | } catch (IOException e) { 78 | e.printStackTrace(); 79 | } 80 | } 81 | return st.nextToken(); 82 | } 83 | 84 | int nextInt() { 85 | return Integer.parseInt(next()); 86 | } 87 | } 88 | } 89 | 90 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/3_improving_quicksort/Sorting.kt: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader 2 | import java.io.IOException 3 | import java.io.InputStream 4 | import java.io.InputStreamReader 5 | import java.util.* 6 | 7 | private val random = Random() 8 | 9 | fun partition3(a: IntArray, l: Int, r: Int): IntArray { 10 | //write your code here 11 | return intArrayOf(l, r) 12 | } 13 | 14 | fun partition2(a: IntArray, l: Int, r: Int): Int { 15 | val x = a[l] 16 | var j = l 17 | for (i in l + 1..r) { 18 | if (a[i] <= x) { 19 | j++ 20 | val t = a[i] 21 | a[i] = a[j] 22 | a[j] = t 23 | } 24 | } 25 | val t = a[l] 26 | a[l] = a[j] 27 | a[j] = t 28 | return j 29 | } 30 | 31 | fun randomizedQuickSort(a: IntArray, l: Int, r: Int) { 32 | if (l >= r) { 33 | return 34 | } 35 | val k = random.nextInt(r - l + 1) + l 36 | val t = a[l] 37 | a[l] = a[k] 38 | a[k] = t 39 | //use partition3 40 | val m = partition2(a, l, r) 41 | randomizedQuickSort(a, l, m - 1) 42 | randomizedQuickSort(a, m + 1, r) 43 | } 44 | 45 | fun main(args: Array) { 46 | val scanner = FastScanner(System.`in`) 47 | val n = scanner.nextInt() 48 | val a = IntArray(n) 49 | for (i in 0 until n) { 50 | a[i] = scanner.nextInt() 51 | } 52 | randomizedQuickSort(a, 0, n - 1) 53 | for (i in 0 until n) { 54 | print(a[i].toString() + " ") 55 | } 56 | } 57 | 58 | class FastScanner(stream: InputStream) { 59 | var br: BufferedReader = BufferedReader(InputStreamReader(stream)) 60 | var st: StringTokenizer? = null 61 | 62 | fun next(): String { 63 | while (st == null || !st!!.hasMoreTokens()) { 64 | try { 65 | st = StringTokenizer(br.readLine()) 66 | } catch (e: IOException) { 67 | e.printStackTrace() 68 | } 69 | } 70 | return st!!.nextToken() 71 | } 72 | 73 | fun nextInt() = next().toInt() 74 | } -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/3_improving_quicksort/by_learners/sorting.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def partition3(a, l, r) 5 | #write your code here 6 | 7 | end 8 | 9 | def partition2(a, l, r) 10 | x = a[l] 11 | j = l 12 | (l + 1..r).each do |i| 13 | if a[i] <= x 14 | j += 1 15 | a[i], a[j] = a[j], a[i] 16 | end 17 | end 18 | a[l], a[j] = a[j], a[l] 19 | j 20 | end 21 | 22 | def randomized_quick_sort(a, l, r) 23 | return nil if l >= r 24 | 25 | k = rand(l..r) 26 | a[l], a[k] = a[k], a[l] 27 | # use partition3 28 | m = partition2(a, l, r) 29 | randomized_quick_sort(a, l, m - 1); 30 | randomized_quick_sort(a, m + 1, r); 31 | end 32 | 33 | if __FILE__ == $0 34 | n, *a = STDIN.read.split().map(&:to_i) 35 | randomized_quick_sort(a, 0, n - 1) 36 | puts "#{a.join(' ')}" 37 | end 38 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/3_improving_quicksort/sorting.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using std::vector; 6 | using std::swap; 7 | 8 | int partition2(vector &a, int l, int r) { 9 | int x = a[l]; 10 | int j = l; 11 | for (int i = l + 1; i <= r; i++) { 12 | if (a[i] <= x) { 13 | j++; 14 | swap(a[i], a[j]); 15 | } 16 | } 17 | swap(a[l], a[j]); 18 | return j; 19 | } 20 | 21 | void randomized_quick_sort(vector &a, int l, int r) { 22 | if (l >= r) { 23 | return; 24 | } 25 | 26 | int k = l + rand() % (r - l + 1); 27 | swap(a[l], a[k]); 28 | int m = partition2(a, l, r); 29 | 30 | randomized_quick_sort(a, l, m - 1); 31 | randomized_quick_sort(a, m + 1, r); 32 | } 33 | 34 | int main() { 35 | int n; 36 | std::cin >> n; 37 | vector a(n); 38 | for (size_t i = 0; i < a.size(); ++i) { 39 | std::cin >> a[i]; 40 | } 41 | randomized_quick_sort(a, 0, a.size() - 1); 42 | for (size_t i = 0; i < a.size(); ++i) { 43 | std::cout << a[i] << ' '; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/3_improving_quicksort/sorting.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | import random 4 | 5 | 6 | def partition3(a, pivot, lo, hi): 7 | 8 | l = lo 9 | r = lo 10 | u = hi 11 | 12 | while r <= u: 13 | if a[r] < pivot: 14 | a[l], a[r] = a[r], a[l] 15 | l += 1 16 | r += 1 17 | elif a[r] > pivot: 18 | a[r], a[u] = a[u], a[r] 19 | u -= 1 20 | else: 21 | r += 1 22 | return l, r 23 | 24 | 25 | def partition2(a, l, r): 26 | x = a[l] 27 | j = l 28 | for i in range(l + 1, r + 1): 29 | if a[i] <= x: 30 | j += 1 31 | a[i], a[j] = a[j], a[i] 32 | a[l], a[j] = a[j], a[l] 33 | return j 34 | 35 | 36 | def randomized_quick_sort(a, lo, hi): 37 | if lo >= hi: 38 | return 39 | pivot = random.randint(lo, hi) 40 | left, right = partition3(a, pivot, lo, hi) 41 | randomized_quick_sort(a, lo, left - 1) 42 | randomized_quick_sort(a, right, hi) 43 | 44 | 45 | if __name__ == "__main__": 46 | input = sys.stdin.read() 47 | n, *a = list(map(int, input.split())) 48 | randomized_quick_sort(a, 0, n - 1) 49 | for x in a: 50 | print(x, end=" ") 51 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/4_number_of_inversions/Inversions.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Inversions { 4 | 5 | private static long getNumberOfInversions(int[] a, int[] b, int left, int right) { 6 | long numberOfInversions = 0; 7 | if (right <= left + 1) { 8 | return numberOfInversions; 9 | } 10 | int ave = (left + right) / 2; 11 | numberOfInversions += getNumberOfInversions(a, b, left, ave); 12 | numberOfInversions += getNumberOfInversions(a, b, ave, right); 13 | //write your code here 14 | return numberOfInversions; 15 | } 16 | 17 | public static void main(String[] args) { 18 | Scanner scanner = new Scanner(System.in); 19 | int n = scanner.nextInt(); 20 | int[] a = new int[n]; 21 | for (int i = 0; i < n; i++) { 22 | a[i] = scanner.nextInt(); 23 | } 24 | int[] b = new int[n]; 25 | System.out.println(getNumberOfInversions(a, b, 0, a.length)); 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/4_number_of_inversions/Inversions.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun getNumberOfInversions(a: IntArray, b: IntArray, left: Int, right: Int): Long { 4 | var numberOfInversions: Long = 0 5 | if (right <= left + 1) { 6 | return numberOfInversions 7 | } 8 | val ave = (left + right) / 2 9 | numberOfInversions += getNumberOfInversions(a, b, left, ave) 10 | numberOfInversions += getNumberOfInversions(a, b, ave, right) 11 | //write your code here 12 | return numberOfInversions 13 | } 14 | 15 | fun main(args: Array) { 16 | val scanner = Scanner(System.`in`) 17 | val n = scanner.nextInt() 18 | val a = IntArray(n) 19 | for (i in 0 until n) { 20 | a[i] = scanner.nextInt() 21 | } 22 | val b = IntArray(n) 23 | println(getNumberOfInversions(a, b, 0, a.size)) 24 | } -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/4_number_of_inversions/by_learners/inversions.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | # helper function for faster copy 5 | # b[l..r - 1] = a[l..r] 6 | def copy(a, b, l, r) 7 | while l < r 8 | b[l] = a[l] 9 | l += 1 10 | end 11 | end 12 | 13 | def get_number_of_inversions(a, b, left, right) 14 | number_of_inversions = 0 15 | return 0 if right - left <= 1 16 | 17 | mid = left + (right - left) / 2 18 | number_of_inversions += get_number_of_inversions(a, b, left, mid) 19 | number_of_inversions += get_number_of_inversions(a, b, mid, right) 20 | #write your code here 21 | 22 | return number_of_inversions 23 | end 24 | 25 | if __FILE__ == $0 26 | n, *a = STDIN.read.split().map(&:to_i) 27 | b = Array.new(n, 0) 28 | puts get_number_of_inversions(a, b, 0, n) 29 | end 30 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/4_number_of_inversions/inversions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::vector; 5 | 6 | long long get_number_of_inversions(vector &a, vector &b, size_t left, size_t right) { 7 | long long number_of_inversions = 0; 8 | if (right <= left + 1) return number_of_inversions; 9 | size_t ave = left + (right - left) / 2; 10 | number_of_inversions += get_number_of_inversions(a, b, left, ave); 11 | number_of_inversions += get_number_of_inversions(a, b, ave, right); 12 | //write your code here 13 | return number_of_inversions; 14 | } 15 | 16 | int main() { 17 | int n; 18 | std::cin >> n; 19 | vector a(n); 20 | for (size_t i = 0; i < a.size(); i++) { 21 | std::cin >> a[i]; 22 | } 23 | vector b(a.size()); 24 | std::cout << get_number_of_inversions(a, b, 0, a.size()) << '\n'; 25 | } 26 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/4_number_of_inversions/inversions.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | 5 | def merge_sort(arr): 6 | 7 | inversion_count = 0 8 | 9 | if len(arr) <= 1: 10 | return inversion_count 11 | 12 | else: 13 | mid = len(arr) // 2 14 | left = arr[:mid] 15 | right = arr[mid:] 16 | 17 | merge_sort(left) 18 | merge_sort(right) 19 | 20 | i = j = k = 0 21 | 22 | # Merging arrays 23 | while i < len(left) and j < len(right): 24 | if left[i] <= right[j]: 25 | 26 | arr[k] = left[i] 27 | i += 1 28 | else: 29 | arr[k] = right[j] 30 | inversion_count += 1 31 | j += 1 32 | k += 1 33 | 34 | # Account for left over elements 35 | while i < len(left): 36 | arr[k] = left[i] 37 | i += 1 38 | k += 1 39 | 40 | while j < len(right): 41 | arr[k] = right[j] 42 | j += 1 43 | k += 1 44 | 45 | return inversion_count 46 | 47 | 48 | # Function to Use Inversion Count 49 | def mergeSort(arr, n): 50 | # A temp_arr is created to store 51 | # sorted array in merge function 52 | temp_arr = [0] * n 53 | return _mergeSort(arr, temp_arr, 0, n - 1) 54 | 55 | 56 | # This Function will use MergeSort to count inversions 57 | 58 | 59 | def _mergeSort(arr, temp_arr, left, right): 60 | 61 | # A variable inv_count is used to store 62 | # inversion counts in each recursive call 63 | 64 | inv_count = 0 65 | 66 | # We will make a recursive call if and only if 67 | # we have more than one elements 68 | 69 | if left < right: 70 | 71 | # mid is calculated to divide the array into two subarrays 72 | # Floor division is must in case of python 73 | 74 | mid = (left + right) // 2 75 | 76 | # It will calculate inversion counts in the left subarray 77 | 78 | inv_count = _mergeSort(arr, temp_arr, left, mid) 79 | 80 | # It will calculate inversion counts in right subarray 81 | 82 | inv_count += _mergeSort(arr, temp_arr, mid + 1, right) 83 | 84 | # It will merge two subarrays in a sorted subarray 85 | 86 | inv_count += merge(arr, temp_arr, left, mid, right) 87 | return inv_count 88 | 89 | 90 | # This function will merge two subarrays in a single sorted subarray 91 | def merge(arr, temp_arr, left, mid, right): 92 | i = left # Starting index of left subarray 93 | j = mid + 1 # Starting index of right subarray 94 | k = left # Starting index of to be sorted subarray 95 | inv_count = 0 96 | 97 | # Conditions are checked to make sure that i and j don't exceed their 98 | # subarray limits. 99 | 100 | while i <= mid and j <= right: 101 | 102 | # There will be no inversion if arr[i] <= arr[j] 103 | 104 | if arr[i] <= arr[j]: 105 | temp_arr[k] = arr[i] 106 | k += 1 107 | i += 1 108 | else: 109 | # Inversion will occur. 110 | temp_arr[k] = arr[j] 111 | inv_count += mid - i + 1 112 | k += 1 113 | j += 1 114 | 115 | # Copy the remaining elements of left subarray into temporary array 116 | while i <= mid: 117 | temp_arr[k] = arr[i] 118 | k += 1 119 | i += 1 120 | 121 | # Copy the remaining elements of right subarray into temporary array 122 | while j <= right: 123 | temp_arr[k] = arr[j] 124 | k += 1 125 | j += 1 126 | 127 | # Copy the sorted subarray into Original array 128 | for loop_var in range(left, right + 1): 129 | arr[loop_var] = temp_arr[loop_var] 130 | 131 | return inv_count 132 | 133 | 134 | def get_number_of_inversions(a, b, left, right): 135 | number_of_inversions = 0 136 | 137 | ave = (left + right) // 2 138 | number_of_inversions += get_number_of_inversions(a, b, left, ave) 139 | number_of_inversions += get_number_of_inversions(a, b, ave, right) 140 | # write your code here 141 | return number_of_inversions 142 | 143 | 144 | if __name__ == "__main__": 145 | input = sys.stdin.read() 146 | n, *a = list(map(int, input.split())) 147 | b = n * [0] 148 | print(mergeSort(a, len(a))) 149 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/5_organizing_a_lottery/PointsAndSegments.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class PointsAndSegments { 4 | 5 | private static int[] fastCountSegments(int[] starts, int[] ends, int[] points) { 6 | int[] cnt = new int[points.length]; 7 | //write your code here 8 | return cnt; 9 | } 10 | 11 | private static int[] naiveCountSegments(int[] starts, int[] ends, int[] points) { 12 | int[] cnt = new int[points.length]; 13 | for (int i = 0; i < points.length; i++) { 14 | for (int j = 0; j < starts.length; j++) { 15 | if (starts[j] <= points[i] && points[i] <= ends[j]) { 16 | cnt[i]++; 17 | } 18 | } 19 | } 20 | return cnt; 21 | } 22 | 23 | public static void main(String[] args) { 24 | Scanner scanner = new Scanner(System.in); 25 | int n, m; 26 | n = scanner.nextInt(); 27 | m = scanner.nextInt(); 28 | int[] starts = new int[n]; 29 | int[] ends = new int[n]; 30 | int[] points = new int[m]; 31 | for (int i = 0; i < n; i++) { 32 | starts[i] = scanner.nextInt(); 33 | ends[i] = scanner.nextInt(); 34 | } 35 | for (int i = 0; i < m; i++) { 36 | points[i] = scanner.nextInt(); 37 | } 38 | //use fastCountSegments 39 | int[] cnt = naiveCountSegments(starts, ends, points); 40 | for (int x : cnt) { 41 | System.out.print(x + " "); 42 | } 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/5_organizing_a_lottery/PointsAndSegments.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun fastCountSegments(starts: IntArray, ends: IntArray, points: IntArray): IntArray { 4 | //write your code here 5 | return IntArray(points.size) 6 | } 7 | 8 | fun naiveCountSegments(starts: IntArray, ends: IntArray, points: IntArray): IntArray { 9 | val cnt = IntArray(points.size) 10 | for (i in points.indices) { 11 | for (j in starts.indices) { 12 | if (starts[j] <= points[i] && points[i] <= ends[j]) { 13 | cnt[i]++ 14 | } 15 | } 16 | } 17 | return cnt 18 | } 19 | 20 | fun main(args: Array) { 21 | val scanner = Scanner(System.`in`) 22 | val n: Int 23 | val m: Int 24 | n = scanner.nextInt() 25 | m = scanner.nextInt() 26 | val starts = IntArray(n) 27 | val ends = IntArray(n) 28 | val points = IntArray(m) 29 | for (i in 0 until n) { 30 | starts[i] = scanner.nextInt() 31 | ends[i] = scanner.nextInt() 32 | } 33 | for (i in 0 until m) { 34 | points[i] = scanner.nextInt() 35 | } 36 | //use fastCountSegments 37 | val cnt = naiveCountSegments(starts, ends, points) 38 | for (x in cnt) { 39 | print(x.toString() + " ") 40 | } 41 | } -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/5_organizing_a_lottery/by_learners/points_and_segments.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | Segment = Struct.new("Segment", :a, :b) do 5 | def contains?(point) 6 | a <= point and point <= b 7 | end 8 | end 9 | 10 | def fast_count_segments(segments, points) 11 | count = Array.new(points.size, 0) 12 | # write your code here 13 | count 14 | end 15 | 16 | def naive_count_segments(segments, points) 17 | points.map { |point| segments.count { |s| s.contains?(point) } } 18 | end 19 | 20 | if __FILE__ == $0 21 | data = STDIN.read.split().map(&:to_i) 22 | s, p = data[0], data[1] 23 | segments = data[2..2*s+1].each_slice(2).to_a.map { |e| Segment.new(e[0], e[1]) } 24 | points = data[2*s+2..-1] 25 | # replace naive with fast 26 | puts naive_count_segments(segments, points).join(' ') 27 | end 28 | 29 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/5_organizing_a_lottery/points_and_segments.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::vector; 5 | 6 | vector fast_count_segments(vector starts, vector ends, vector points) { 7 | vector cnt(points.size()); 8 | //write your code here 9 | return cnt; 10 | } 11 | 12 | vector naive_count_segments(vector starts, vector ends, vector points) { 13 | vector cnt(points.size()); 14 | for (size_t i = 0; i < points.size(); i++) { 15 | for (size_t j = 0; j < starts.size(); j++) { 16 | cnt[i] += starts[j] <= points[i] && points[i] <= ends[j]; 17 | } 18 | } 19 | return cnt; 20 | } 21 | 22 | int main() { 23 | int n, m; 24 | std::cin >> n >> m; 25 | vector starts(n), ends(n); 26 | for (size_t i = 0; i < starts.size(); i++) { 27 | std::cin >> starts[i] >> ends[i]; 28 | } 29 | vector points(m); 30 | for (size_t i = 0; i < points.size(); i++) { 31 | std::cin >> points[i]; 32 | } 33 | //use fast_count_segments 34 | vector cnt = naive_count_segments(starts, ends, points); 35 | for (size_t i = 0; i < cnt.size(); i++) { 36 | std::cout << cnt[i] << ' '; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/5_organizing_a_lottery/points_and_segments.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import random 3 | import sys 4 | from collections import defaultdict 5 | 6 | 7 | def fast_count_segments(starts, ends, points): 8 | cnt = [0] * len(points) 9 | left = 1 10 | point = 2 11 | right = 3 12 | 13 | starts_left = [left] * len(starts) 14 | ends_right = [right] * len(ends) 15 | points_p = [point] * len(points) 16 | 17 | pairs_number = starts + ends + points 18 | pairs_letter = starts_left + ends_right + points_p 19 | 20 | randomized_quick_sort(pairs_number, pairs_letter, 0, len(pairs_number) - 1) 21 | 22 | count_left = 0 23 | point_counts = defaultdict(int) 24 | 25 | for i in range(len(pairs_number)): 26 | if pairs_letter[i] == left: 27 | count_left += 1 28 | elif pairs_letter[i] == right: 29 | count_left -= 1 30 | elif pairs_letter[i] == point: 31 | if point_counts[pairs_number[i]] == 0: 32 | point_counts[pairs_number[i]] += count_left 33 | 34 | for i in range(len(points)): 35 | cnt[i] = point_counts[points[i]] 36 | 37 | return cnt 38 | 39 | 40 | def naive_count_segments(starts, ends, points): 41 | cnt = [0] * len(points) 42 | for i in range(len(points)): 43 | for j in range(len(starts)): 44 | if starts[j] <= points[i] <= ends[j]: 45 | cnt[i] += 1 46 | return cnt 47 | 48 | 49 | def partition3(a, b, l, r): 50 | x = a[l] 51 | letx = b[l] 52 | begin = l + 1 53 | end = l 54 | 55 | for i in range(l + 1, r + 1): 56 | if less_than_or_equal(a[i], x, b[i], letx): 57 | end += 1 58 | a[i], a[end] = a[end], a[i] 59 | b[i], b[end] = b[end], b[i] 60 | if less_than(a[end], x, b[end], letx): 61 | a[begin], a[end] = a[end], a[begin] 62 | b[begin], b[end] = b[end], b[begin] 63 | begin += 1 64 | 65 | a[l], a[begin - 1] = a[begin - 1], a[l] 66 | b[l], b[begin - 1] = b[begin - 1], b[l] 67 | 68 | return [begin, end] 69 | 70 | 71 | def less_than_or_equal(num1, num2, let1, let2): 72 | return less_than(num1, num2, let1, let2) or equal(num1, num2, let1, let2) 73 | 74 | 75 | def less_than(num1, num2, let1, let2): 76 | return num1 < num2 or (num1 == num2 and let1 < let2) 77 | 78 | 79 | def equal(num1, num2, let1, let2): 80 | return num1 == num2 and let1 == let2 81 | 82 | 83 | def randomized_quick_sort(a, b, l, r): 84 | if l >= r: 85 | return 86 | k = random.randint(l, r) 87 | a[l], a[k] = a[k], a[l] 88 | b[l], b[k] = b[k], b[l] 89 | # use partition3 90 | [m1, m2] = partition3(a, b, l, r) 91 | randomized_quick_sort(a, b, l, m1 - 1) 92 | randomized_quick_sort(a, b, m2 + 1, r) 93 | 94 | 95 | if __name__ == "__main__": 96 | input = sys.stdin.read() 97 | data = list(map(int, input.split())) 98 | n = data[0] 99 | m = data[1] 100 | starts = data[2 : 2 * n + 2 : 2] 101 | ends = data[3 : 2 * n + 2 : 2] 102 | points = data[2 * n + 2 :] 103 | # use fast_count_segments 104 | cnt = fast_count_segments(starts, ends, points) 105 | for x in cnt: 106 | print(x, end=" ") 107 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/6_closest_points/Closest.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | import static java.lang.Math.*; 5 | 6 | public class Closest { 7 | 8 | static class Point implements Comparable { 9 | long x, y; 10 | 11 | public Point(long x, long y) { 12 | this.x = x; 13 | this.y = y; 14 | } 15 | 16 | @Override 17 | public int compareTo(Point o) { 18 | return o.y == y ? Long.signum(x - o.x) : Long.signum(y - o.y); 19 | } 20 | } 21 | 22 | static double minimalDistance(int[] x, int y[]) { 23 | double ans = Double.POSITIVE_INFINITY; 24 | //write your code here 25 | return ans; 26 | } 27 | 28 | public static void main(String[] args) throws Exception { 29 | reader = new BufferedReader(new InputStreamReader(System.in)); 30 | writer = new PrintWriter(System.out); 31 | int n = nextInt(); 32 | int[] x = new int[n]; 33 | int[] y = new int[n]; 34 | for (int i = 0; i < n; i++) { 35 | x[i] = nextInt(); 36 | y[i] = nextInt(); 37 | } 38 | System.out.println(minimalDistance(x, y)); 39 | writer.close(); 40 | } 41 | 42 | static BufferedReader reader; 43 | static PrintWriter writer; 44 | static StringTokenizer tok = new StringTokenizer(""); 45 | 46 | 47 | static String next() { 48 | while (!tok.hasMoreTokens()) { 49 | String w = null; 50 | try { 51 | w = reader.readLine(); 52 | } catch (Exception e) { 53 | e.printStackTrace(); 54 | } 55 | if (w == null) 56 | return null; 57 | tok = new StringTokenizer(w); 58 | } 59 | return tok.nextToken(); 60 | } 61 | 62 | static int nextInt() { 63 | return Integer.parseInt(next()); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/6_closest_points/Closest.kt: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader 2 | import java.io.InputStreamReader 3 | import java.io.PrintWriter 4 | import java.util.* 5 | 6 | var tok = StringTokenizer("") 7 | 8 | class Point(var x: Long, var y: Long) : Comparable { 9 | override fun compareTo(other: Point): Int { 10 | return if (other.y == y) java.lang.Long.signum(x - other.x) 11 | else java.lang.Long.signum(y - other.y) 12 | } 13 | } 14 | 15 | fun minimalDistance(x: IntArray, y: IntArray): Double { 16 | //write your code here 17 | return java.lang.Double.POSITIVE_INFINITY 18 | } 19 | 20 | fun main(args: Array) { 21 | val writer = PrintWriter(System.out) 22 | val reader = BufferedReader(InputStreamReader(System.`in`)) 23 | val n = nextInt(reader) 24 | val x = IntArray(n) 25 | val y = IntArray(n) 26 | for (i in 0 until n) { 27 | x[i] = nextInt(reader) 28 | y[i] = nextInt(reader) 29 | } 30 | println(minimalDistance(x, y)) 31 | writer.close() 32 | } 33 | 34 | 35 | fun next(reader: BufferedReader): String? { 36 | while (!tok.hasMoreTokens()) { 37 | var w: String? = null 38 | try { 39 | w = reader.readLine() 40 | } catch (e: Exception) { 41 | e.printStackTrace() 42 | } 43 | 44 | if (w == null) 45 | return null 46 | tok = StringTokenizer(w) 47 | } 48 | return tok.nextToken() 49 | } 50 | 51 | fun nextInt(reader: BufferedReader): Int { 52 | return next(reader)!!.toInt() 53 | } -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/6_closest_points/by_learners/closest.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def min(a, b) 5 | a < b ? a : b 6 | end 7 | 8 | def minimum_distance(x, y) 9 | # write your code here 10 | Math.sqrt(10 ** 36) 11 | end 12 | 13 | if __FILE__ == $0 14 | data = STDIN.read.split().map(&:to_i) 15 | n = data.size - 1 16 | x = (1..n).step(2).map { |i| data[i] } 17 | y = (2..n).step(2).map { |i| data[i] } 18 | puts "#{'%.4f' % minimum_distance(x, y)}" 19 | end -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/6_closest_points/closest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using std::vector; 10 | using std::string; 11 | using std::pair; 12 | using std::min; 13 | 14 | 15 | double minimal_distance(vector x, vector y) { 16 | //write your code here 17 | return 0.; 18 | } 19 | 20 | int main() { 21 | size_t n; 22 | std::cin >> n; 23 | vector x(n); 24 | vector y(n); 25 | for (size_t i = 0; i < n; i++) { 26 | std::cin >> x[i] >> y[i]; 27 | } 28 | std::cout << std::fixed; 29 | std::cout << std::setprecision(9) << minimal_distance(x, y) << "\n"; 30 | } 31 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/6_closest_points/closest.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | import math 4 | 5 | 6 | def solve(ax, ay): 7 | a = list(zip(ax, ay)) 8 | ax = sorted(a, key=lambda x: x[0]) 9 | ay = sorted(a, key=lambda x: x[1]) 10 | p1, p2, mi = closest_pair(ax, ay) 11 | return mi 12 | 13 | 14 | def closest_pair(ax, ay): 15 | len_ax = len(ax) 16 | if len_ax <= 3: 17 | return brute(ax) 18 | 19 | mid = len_ax // 2 20 | q_x = ax[:mid] 21 | r_x = ax[mid:] 22 | 23 | midpoint = ax[mid][0] 24 | q_y = list() 25 | r_y = list() 26 | 27 | for x in ay: 28 | if x[0] <= midpoint: 29 | q_y.append(x) 30 | else: 31 | r_y.append(x) 32 | 33 | (p1, q1, mi1) = closest_pair(q_x, q_y) 34 | (p2, q2, mi2) = closest_pair(r_x, r_y) 35 | 36 | if mi1 <= mi2: 37 | d = mi1 38 | mn = (p1, q1) 39 | else: 40 | d = mi2 41 | mn = (p2, q2) 42 | 43 | (p3, q3, mi3) = closest_split_pair(ax, ay, d, mn) 44 | 45 | if d <= mi3: 46 | return mn[0], mn[1], d 47 | else: 48 | return p3, q3, mi3 49 | 50 | 51 | def brute(ax): 52 | mi = dist(ax[0], ax[1]) 53 | p1 = ax[0] 54 | p2 = ax[1] 55 | len_ax = len(ax) 56 | if len_ax == 2: 57 | return p1, p2, mi 58 | 59 | for i in range(len_ax - 1): 60 | for j in range(i + 1, len_ax): 61 | if i != 0 and j != 1: 62 | d = dist(ax[i], ax[j]) 63 | if d < mi: 64 | mi = d 65 | p1, p2 = ax[i], ax[j] 66 | 67 | return p1, p2, mi 68 | 69 | 70 | import math 71 | 72 | 73 | def dist(x, y): 74 | return math.sqrt((x[1] - x[0]) ** 2 + (y[1] - y[0]) ** 2) 75 | 76 | 77 | def closest_split_pair(p_x, p_y, delta, best_pair): 78 | len_x = len(p_x) 79 | mx_x = p_x[len_x // 2][0] 80 | 81 | s_y = [x for x in p_y if mx_x - delta <= x[0] <= mx_x + delta] 82 | best = delta 83 | len_y = len(s_y) 84 | for i in range(len_y - 1): 85 | for j in range(i + 1, min(i + 7, len_y)): 86 | p, q = s_y[i], s_y[j] 87 | dst = dist(p, q) 88 | if dst < best: 89 | best_pair = p, q 90 | best = dst 91 | 92 | return best_pair[0], best_pair[1], best 93 | 94 | 95 | def minimum_distance(x, y): 96 | # write your code here 97 | return 10 ** 18 98 | 99 | 100 | if __name__ == "__main__": 101 | input = sys.stdin.read() 102 | data = list(map(int, input.split())) 103 | n = data[0] 104 | x = data[1::2] 105 | y = data[2::2] 106 | ax = (x + y)[::2] 107 | ay = (x + y)[1::2] 108 | print("{0:.9f}".format(solve(ax, ay))) 109 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/6_closest_points/closest_points.py: -------------------------------------------------------------------------------- 1 | import math 2 | from dataclasses import dataclass 3 | 4 | 5 | @dataclass 6 | class Point: 7 | x: int 8 | y: int 9 | 10 | 11 | def dist(p1, p2): 12 | return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2) 13 | 14 | 15 | def brute_force(p, n): 16 | min_ = float("inf") 17 | for i in range(n): 18 | for j in range(i + 1, n): 19 | d = dist(p[i], p[j]) 20 | if d < min_: 21 | min_ = d 22 | 23 | return min_ 24 | 25 | 26 | def strip_closest(strip, size, d): 27 | min_ = d 28 | for i in range(size): 29 | for j in range(i + 1, size): 30 | if strip[j].y - strip[i].y < min_: 31 | break 32 | d = dist(strip[i], strip[j]) 33 | if d < min_: 34 | min_ = d 35 | 36 | return min_ 37 | 38 | 39 | def closest_util(px, py, n): 40 | if n <= 3: 41 | return brute_force(px, n) 42 | 43 | mid = n // 2 44 | mid_point = px[mid] 45 | 46 | pyl = [0] * (mid + 1) 47 | pyr = [0] * (n - mid - 1) 48 | 49 | li = 0 50 | ri = 0 51 | 52 | for i in range(n): 53 | if py[i].x <= mid_point.x: 54 | li += 1 55 | pyl[li] = py[i] 56 | else: 57 | ri += 1 58 | pyr[ri] = py[i] 59 | 60 | dl = closest_util(px, pyl, mid) 61 | dr = closest_util(px + mid, pyr, n - mid) 62 | 63 | d = min(dl, dr) 64 | 65 | strip = [0] * n 66 | j = 0 67 | for i in range(n): 68 | if abs(py[i].x - mid_point.x) < d: 69 | strip[j] = py[i] 70 | j += 1 71 | 72 | return min(d, strip_closest(strip, j, d)) 73 | 74 | 75 | def closest(xs, ys): 76 | ps = [Point(x, y) for x, y in zip(xs, ys)] 77 | px = sorted(ps, key=lambda x: x.x) 78 | py = sorted(ps, key=lambda x: x.y) 79 | 80 | return closest_util(px, py, len(px)) 81 | -------------------------------------------------------------------------------- /input/week4_divide_and_conquer/week4_divide_and_conquer.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WillKoehrsen/data-structures-and-algorithms-coursera/d13b5460447d3decc095aa54b883e01d8c8a9860/input/week4_divide_and_conquer/week4_divide_and_conquer.pdf -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/1_money_change_again/ChangeDP.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class ChangeDP { 4 | private static int getChange(int m) { 5 | //write your code here 6 | return m / 4; 7 | } 8 | 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | int m = scanner.nextInt(); 12 | System.out.println(getChange(m)); 13 | 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/1_money_change_again/ChangeDP.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun getChange(m: Int): Int { 4 | //write your code here 5 | return m / 4 6 | } 7 | 8 | fun main(args: Array) { 9 | val scanner = Scanner(System.`in`) 10 | val m = scanner.nextInt() 11 | println(getChange(m)) 12 | } -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/1_money_change_again/change_dp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int get_change(int m) { 4 | //write your code here 5 | return m / 4; 6 | } 7 | 8 | int main() { 9 | int m; 10 | std::cin >> m; 11 | std::cout << get_change(m) << '\n'; 12 | } 13 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/1_money_change_again/change_dp.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | 5 | def get_change(m): 6 | coins = [1, 3, 4] 7 | table = [float("inf") for _ in range(m + 1)] 8 | table[0] = 0 9 | 10 | coin_unique_count = len(coins) 11 | for i in range(1, m + 1): 12 | for j in range(coin_unique_count): 13 | if coins[j] <= i: 14 | sub_res = table[i - coins[j]] 15 | if (sub_res != float("inf")) and (sub_res + 1 < table[i]): 16 | table[i] = sub_res + 1 17 | 18 | return table[m] 19 | 20 | 21 | if __name__ == "__main__": 22 | m = int(sys.stdin.read()) 23 | print(get_change(m)) 24 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/2_primitive_calculator/PrimitiveCalculator.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class PrimitiveCalculator { 4 | private static List optimal_sequence(int n) { 5 | List sequence = new ArrayList(); 6 | while (n >= 1) { 7 | sequence.add(n); 8 | if (n % 3 == 0) { 9 | n /= 3; 10 | } else if (n % 2 == 0) { 11 | n /= 2; 12 | } else { 13 | n -= 1; 14 | } 15 | } 16 | Collections.reverse(sequence); 17 | return sequence; 18 | } 19 | 20 | public static void main(String[] args) { 21 | Scanner scanner = new Scanner(System.in); 22 | int n = scanner.nextInt(); 23 | List sequence = optimal_sequence(n); 24 | System.out.println(sequence.size() - 1); 25 | for (Integer x : sequence) { 26 | System.out.print(x + " "); 27 | } 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/2_primitive_calculator/PrimitiveCalculator.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun optimalSequence(n: Int): List { 4 | var m = n 5 | val sequence = ArrayList() 6 | while (m >= 1) { 7 | sequence.add(m) 8 | when { 9 | m % 3 == 0 -> m /= 3 10 | m % 2 == 0 -> m /= 2 11 | else -> m -= 1 12 | } 13 | } 14 | return sequence.reversed() 15 | } 16 | 17 | fun main(args: Array) { 18 | val scanner = Scanner(System.`in`) 19 | val n = scanner.nextInt() 20 | val sequence = optimalSequence(n) 21 | println(sequence.size - 1) 22 | for (x in sequence) { 23 | print(x.toString() + " ") 24 | } 25 | } -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/2_primitive_calculator/by_learners/primitive_calculator.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def minimum_operations(n) 5 | # change this code 6 | sequence = [] 7 | while n >= 1 8 | sequence.push(n) 9 | case 10 | when n % 3 == 0 11 | n /= 3 12 | when n % 2 == 0 13 | n /= 2 14 | else 15 | n -= 1 16 | end 17 | end 18 | sequence.reverse 19 | 20 | end 21 | 22 | if __FILE__ == $0 23 | n = gets.to_i 24 | answer = minimum_operations(n) 25 | puts answer.length - 1 26 | puts answer.join(' ') 27 | end -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/2_primitive_calculator/primitive_calculator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using std::vector; 6 | 7 | vector optimal_sequence(int n) { 8 | std::vector sequence; 9 | while (n >= 1) { 10 | sequence.push_back(n); 11 | if (n % 3 == 0) { 12 | n /= 3; 13 | } else if (n % 2 == 0) { 14 | n /= 2; 15 | } else { 16 | n = n - 1; 17 | } 18 | } 19 | reverse(sequence.begin(), sequence.end()); 20 | return sequence; 21 | } 22 | 23 | int main() { 24 | int n; 25 | std::cin >> n; 26 | vector sequence = optimal_sequence(n); 27 | std::cout << sequence.size() - 1 << std::endl; 28 | for (size_t i = 0; i < sequence.size(); ++i) { 29 | std::cout << sequence[i] << " "; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/2_primitive_calculator/primitive_calculator.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | 5 | def optimal_sequence(n): 6 | sequence = [] 7 | while n >= 1: 8 | sequence.append(n) 9 | if n % 3 == 0: 10 | n = n // 3 11 | elif n % 2 == 0: 12 | n = n // 2 13 | else: 14 | n = n - 1 15 | return reversed(sequence) 16 | 17 | 18 | d = {} 19 | 20 | 21 | def f(n): 22 | if n == 1: 23 | return 1, -1 24 | if d.get(n) is not None: 25 | return d[n] 26 | ans = (f(n - 1)[0] + 1, n - 1) 27 | 28 | if n % 2 == 0: 29 | ret = f(n // 2) 30 | if ans[0] > ret[0]: 31 | ans = (ret[0] + 1, n // 2) 32 | 33 | if n % 3 == 0: 34 | ret = f(n // 3) 35 | if ans[0] > ret[0]: 36 | ans = (ret[0] + 1, n // 3) 37 | 38 | d[n] = ans 39 | return ans 40 | 41 | 42 | def print_solution(n): 43 | ans = [] 44 | 45 | while f(n)[1] != -1: 46 | ans.append(n) 47 | n = f(n)[1] 48 | 49 | ans.append(1) 50 | ans.reverse() 51 | return ans 52 | 53 | 54 | def solve(n): 55 | for i in range(1, n): 56 | f(i)[0] 57 | ans = print_solution(n) 58 | return ans 59 | 60 | 61 | if __name__ == "__main__": 62 | input = sys.stdin.read() 63 | n = int(input) 64 | sequence = list(solve(n)) 65 | print(len(sequence) - 1) 66 | for x in sequence: 67 | print(x, end=" ") 68 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/3_edit_distance/EditDistance.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class EditDistance { 4 | public static int EditDistance(String s, String t) { 5 | //write your code here 6 | return 0; 7 | } 8 | public static void main(String args[]) { 9 | Scanner scan = new Scanner(System.in); 10 | 11 | String s = scan.next(); 12 | String t = scan.next(); 13 | 14 | System.out.println(EditDistance(s, t)); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/3_edit_distance/EditDistance.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun getEditDistance(s: String, t: String): Int { 4 | //write your code here 5 | return 0 6 | } 7 | 8 | fun main(args: Array) { 9 | val scan = Scanner(System.`in`) 10 | 11 | val s = scan.next() 12 | val t = scan.next() 13 | 14 | println(getEditDistance(s, t)) 15 | } -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/3_edit_distance/by_learners/edit_distance.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def edit_distance(a, b) 5 | # write your code here 6 | 0 7 | end 8 | 9 | if __FILE__ == $0 10 | a, b = gets, gets 11 | puts edit_distance(a, b) 12 | end 13 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/3_edit_distance/edit_distance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::string; 5 | 6 | int edit_distance(const string &str1, const string &str2) { 7 | //write your code here 8 | return 0; 9 | } 10 | 11 | int main() { 12 | string str1; 13 | string str2; 14 | std::cin >> str1 >> str2; 15 | std::cout << edit_distance(str1, str2) << std::endl; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/3_edit_distance/edit_distance.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | def edit_distance(s, t): 3 | # write your code here 4 | return 0 5 | 6 | 7 | def levenshtein_distance(s1, s2): 8 | if len(s1) > len(s2): 9 | s1, s2 = s2, s1 10 | 11 | distances = range(len(s1) + 1) 12 | 13 | for i2, c2 in enumerate(s2): 14 | distances_ = [i2 + 1] 15 | for i1, c1 in enumerate(s1): 16 | if c1 == c2: 17 | distances_.append(distances[i1]) 18 | 19 | else: 20 | distances_.append( 21 | 1 + min((distances[i1], distances[i1 + 1], distances_[-1])) 22 | ) 23 | 24 | distances = distances_ 25 | return distances[-1] 26 | 27 | 28 | if __name__ == "__main__": 29 | print(levenshtein_distance(input(), input())) 30 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/4_longest_common_subsequence_of_two_sequences/LCS2.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class LCS2 { 4 | 5 | private static int lcs2(int[] a, int[] b) { 6 | //Write your code here 7 | return Math.min(a.length, b.length); 8 | } 9 | 10 | public static void main(String[] args) { 11 | Scanner scanner = new Scanner(System.in); 12 | int n = scanner.nextInt(); 13 | int[] a = new int[n]; 14 | for (int i = 0; i < n; i++) { 15 | a[i] = scanner.nextInt(); 16 | } 17 | 18 | int m = scanner.nextInt(); 19 | int[] b = new int[m]; 20 | for (int i = 0; i < m; i++) { 21 | b[i] = scanner.nextInt(); 22 | } 23 | 24 | System.out.println(lcs2(a, b)); 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/4_longest_common_subsequence_of_two_sequences/LCS2.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | import kotlin.math.min 3 | 4 | fun lcs2(a: IntArray, b: IntArray): Int { 5 | //Write your code here 6 | return min(a.size, b.size) 7 | } 8 | 9 | fun main(args: Array) { 10 | val scanner = Scanner(System.`in`) 11 | val n = scanner.nextInt() 12 | val a = IntArray(n) 13 | for (i in 0 until n) { 14 | a[i] = scanner.nextInt() 15 | } 16 | 17 | val m = scanner.nextInt() 18 | val b = IntArray(m) 19 | for (i in 0 until m) { 20 | b[i] = scanner.nextInt() 21 | } 22 | 23 | println(lcs2(a, b)) 24 | } -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/4_longest_common_subsequence_of_two_sequences/lcs2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::vector; 5 | 6 | int lcs2(vector &a, vector &b) { 7 | //write your code here 8 | return std::min(std::min(a.size(), b.size()), c.size()); 9 | } 10 | 11 | int main() { 12 | size_t n; 13 | std::cin >> n; 14 | vector a(n); 15 | for (size_t i = 0; i < n; i++) { 16 | std::cin >> a[i]; 17 | } 18 | 19 | size_t m; 20 | std::cin >> m; 21 | vector b(m); 22 | for (size_t i = 0; i < m; i++) { 23 | std::cin >> b[i]; 24 | } 25 | 26 | std::cout << lcs2(a, b) << std::endl; 27 | } 28 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/4_longest_common_subsequence_of_two_sequences/lcs2.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | 3 | import sys 4 | 5 | 6 | def lcs2(X, Y): 7 | m = len(X) 8 | n = len(Y) 9 | 10 | # Empty array for storing dp values 11 | L = [[None] * (n + 1) for i in range(m + 1)] 12 | 13 | # Build up the dp table values 14 | for i in range(m + 1): 15 | for j in range(n + 1): 16 | if i == 0 or j == 0: 17 | L[i][j] = 0 18 | elif X[i - 1] == Y[j - 1]: 19 | L[i][j] = L[i - 1][j - 1] + 1 20 | else: 21 | L[i][j] = max(L[i - 1][j], L[i][j - 1]) 22 | 23 | return L[m][n] 24 | 25 | 26 | if __name__ == "__main__": 27 | input = sys.stdin.read() 28 | data = list(map(int, input.split())) 29 | 30 | n = data[0] 31 | data = data[1:] 32 | a = data[:n] 33 | 34 | data = data[n:] 35 | m = data[0] 36 | data = data[1:] 37 | b = data[:m] 38 | 39 | print(lcs2(a, b)) 40 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/5_longest_common_subsequence_of_three_sequences/LCS3.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class LCS3 { 4 | 5 | private static int lcs3(int[] a, int[] b, int[] c) { 6 | //Write your code here 7 | return Math.min(Math.min(a.length, b.length), c.length); 8 | } 9 | 10 | public static void main(String[] args) { 11 | Scanner scanner = new Scanner(System.in); 12 | int an = scanner.nextInt(); 13 | int[] a = new int[an]; 14 | for (int i = 0; i < an; i++) { 15 | a[i] = scanner.nextInt(); 16 | } 17 | int bn = scanner.nextInt(); 18 | int[] b = new int[bn]; 19 | for (int i = 0; i < bn; i++) { 20 | b[i] = scanner.nextInt(); 21 | } 22 | int cn = scanner.nextInt(); 23 | int[] c = new int[cn]; 24 | for (int i = 0; i < cn; i++) { 25 | c[i] = scanner.nextInt(); 26 | } 27 | System.out.println(lcs3(a, b, c)); 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/5_longest_common_subsequence_of_three_sequences/LCS3.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | import kotlin.math.min 3 | 4 | fun lcs3(a: IntArray, b: IntArray, c: IntArray): Int { 5 | //Write your code here 6 | return min(min(a.size, b.size), c.size) 7 | } 8 | 9 | fun main(args: Array) { 10 | val scanner = Scanner(System.`in`) 11 | val an = scanner.nextInt() 12 | val a = IntArray(an) 13 | for (i in 0 until an) { 14 | a[i] = scanner.nextInt() 15 | } 16 | val bn = scanner.nextInt() 17 | val b = IntArray(bn) 18 | for (i in 0 until bn) { 19 | b[i] = scanner.nextInt() 20 | } 21 | val cn = scanner.nextInt() 22 | val c = IntArray(cn) 23 | for (i in 0 until cn) { 24 | c[i] = scanner.nextInt() 25 | } 26 | println(lcs3(a, b, c)) 27 | } -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/5_longest_common_subsequence_of_three_sequences/by_learners/lcs3.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def lcs3(a, b, c) 5 | # write your code here 6 | [a.size, b.size, c.size].min 7 | end 8 | 9 | if __FILE__ == $0 10 | data = STDIN.read.split().map(&:to_i) 11 | n = data[0] 12 | a = data[1..n] 13 | m = data[n+1] 14 | b = data[n+2..n+1+m] 15 | c = data[n+3+m..-1] 16 | puts lcs3(a, b, c) 17 | end 18 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/5_longest_common_subsequence_of_three_sequences/lcs3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::vector; 5 | 6 | int lcs3(vector &a, vector &b, vector &c) { 7 | //write your code here 8 | return std::min(std::min(a.size(), b.size()), c.size()); 9 | } 10 | 11 | int main() { 12 | size_t an; 13 | std::cin >> an; 14 | vector a(an); 15 | for (size_t i = 0; i < an; i++) { 16 | std::cin >> a[i]; 17 | } 18 | size_t bn; 19 | std::cin >> bn; 20 | vector b(bn); 21 | for (size_t i = 0; i < bn; i++) { 22 | std::cin >> b[i]; 23 | } 24 | size_t cn; 25 | std::cin >> cn; 26 | vector c(cn); 27 | for (size_t i = 0; i < cn; i++) { 28 | std::cin >> c[i]; 29 | } 30 | std::cout << lcs3(a, b, c) << std::endl; 31 | } 32 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/5_longest_common_subsequence_of_three_sequences/lcs3.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | 3 | import sys 4 | 5 | 6 | def lcs3(X, Y, Z): 7 | m = len(X) 8 | n = len(Y) 9 | o = len(Z) 10 | 11 | # Initialize the dp table 12 | L = [[[0 for i in range(o + 1)] for j in range(n + 1)] for k in range(m + 1)] 13 | 14 | # Build up dp table 15 | for i in range(m + 1): 16 | for j in range(n + 1): 17 | for k in range(o + 1): 18 | if i == 0 or j == 0 or k == 0: 19 | L[i][j][k] = 0 20 | elif X[i - 1] == Y[j - 1] and X[i - 1] == Z[k - 1]: 21 | L[i][j][k] = L[i - 1][j - 1][k - 1] + 1 22 | else: 23 | L[i][j][k] = max( 24 | max(L[i - 1][j][k], L[i][j - 1][k]), L[i][j][k - 1] 25 | ) 26 | 27 | return L[m][n][o] 28 | 29 | 30 | if __name__ == "__main__": 31 | input = sys.stdin.read() 32 | data = list(map(int, input.split())) 33 | an = data[0] 34 | data = data[1:] 35 | a = data[:an] 36 | data = data[an:] 37 | bn = data[0] 38 | data = data[1:] 39 | b = data[:bn] 40 | data = data[bn:] 41 | cn = data[0] 42 | data = data[1:] 43 | c = data[:cn] 44 | print(lcs3(a, b, c)) 45 | -------------------------------------------------------------------------------- /input/week5_dynamic_programming1/week5_dynamic_programming1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WillKoehrsen/data-structures-and-algorithms-coursera/d13b5460447d3decc095aa54b883e01d8c8a9860/input/week5_dynamic_programming1/week5_dynamic_programming1.pdf -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/1_maximum_amount_of_gold/Knapsack.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Knapsack { 4 | static int optimalWeight(int W, int[] w) { 5 | //write you code here 6 | int result = 0; 7 | for (int i = 0; i < w.length; i++) { 8 | if (result + w[i] <= W) { 9 | result += w[i]; 10 | } 11 | } 12 | return result; 13 | } 14 | 15 | public static void main(String[] args) { 16 | Scanner scanner = new Scanner(System.in); 17 | int W, n; 18 | W = scanner.nextInt(); 19 | n = scanner.nextInt(); 20 | int[] w = new int[n]; 21 | for (int i = 0; i < n; i++) { 22 | w[i] = scanner.nextInt(); 23 | } 24 | System.out.println(optimalWeight(W, w)); 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/1_maximum_amount_of_gold/Knapsack.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun optimalWeight(w: Int, array: IntArray): Int { 4 | //write you code here 5 | var result = 0 6 | for (i in array.indices) { 7 | if (result + array[i] <= w) { 8 | result += array[i] 9 | } 10 | } 11 | return result 12 | } 13 | 14 | fun main(args: Array) { 15 | val scanner = Scanner(System.`in`) 16 | val w: Int 17 | val n: Int 18 | w = scanner.nextInt() 19 | n = scanner.nextInt() 20 | val array = IntArray(n) 21 | for (i in 0 until n) { 22 | array[i] = scanner.nextInt() 23 | } 24 | println(optimalWeight(w, array)) 25 | } -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/1_maximum_amount_of_gold/by_learners/knapsack.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | def optimal_weight(w, weights) 5 | # write your code here 6 | result = 0 7 | weights.each { |weight| result += weight if result + weight <= w } 8 | result 9 | end 10 | 11 | if __FILE__ == $0 12 | w, _, *weights = STDIN.read.split().map(&:to_i) 13 | puts optimal_weight(w, weights) 14 | end 15 | -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/1_maximum_amount_of_gold/knapsack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::vector; 5 | 6 | int optimal_weight(int W, const vector &w) { 7 | //write your code here 8 | int current_weight = 0; 9 | for (size_t i = 0; i < w.size(); ++i) { 10 | if (current_weight + w[i] <= W) { 11 | current_weight += w[i]; 12 | } 13 | } 14 | return current_weight; 15 | } 16 | 17 | int main() { 18 | int n, W; 19 | std::cin >> W >> n; 20 | vector w(n); 21 | for (int i = 0; i < n; i++) { 22 | std::cin >> w[i]; 23 | } 24 | std::cout << optimal_weight(W, w) << '\n'; 25 | } 26 | -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/1_maximum_amount_of_gold/knapsack.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | 5 | def optimal_weight(W, w): 6 | # write your code here 7 | result = 0 8 | for x in w: 9 | if result + x <= W: 10 | result = result + x 11 | return result 12 | 13 | 14 | if __name__ == "__main__": 15 | input = sys.stdin.read() 16 | W, n, *w = list(map(int, input.split())) 17 | print(optimal_weight(W, w)) 18 | -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/2_partitioning_souvenirs/Partition3.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class Partition3 { 5 | private static int partition3(int[] A) { 6 | //write your code here 7 | return 0; 8 | } 9 | 10 | public static void main(String[] args) { 11 | Scanner scanner = new Scanner(System.in); 12 | int n = scanner.nextInt(); 13 | int[] A = new int[n]; 14 | for (int i = 0; i < n; i++) { 15 | A[i] = scanner.nextInt(); 16 | } 17 | System.out.println(partition3(A)); 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/2_partitioning_souvenirs/Partition3.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun partition3(array: IntArray): Int { 4 | //write your code here 5 | return 0 6 | } 7 | 8 | fun main(args: Array) { 9 | val scanner = Scanner(System.`in`) 10 | val n = scanner.nextInt() 11 | val array = IntArray(n) 12 | for (i in 0 until n) { 13 | array[i] = scanner.nextInt() 14 | } 15 | println(partition3(array)) 16 | } -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/2_partitioning_souvenirs/partition3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::vector; 5 | 6 | int partition3(vector &A) { 7 | //write your code here 8 | return 0; 9 | } 10 | 11 | int main() { 12 | int n; 13 | std::cin >> n; 14 | vector A(n); 15 | for (size_t i = 0; i < A.size(); ++i) { 16 | std::cin >> A[i]; 17 | } 18 | std::cout << partition3(A) << '\n'; 19 | } 20 | -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/2_partitioning_souvenirs/partition3.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | import itertools 4 | 5 | 6 | def partition3(A): 7 | for c in itertools.product(range(3), repeat=len(A)): 8 | sums = [None] * 3 9 | for i in range(3): 10 | sums[i] = sum(A[k] for k in range(len(A)) if c[k] == i) 11 | 12 | if sums[0] == sums[1] and sums[1] == sums[2]: 13 | return 1 14 | 15 | return 0 16 | 17 | 18 | if __name__ == "__main__": 19 | input = sys.stdin.read() 20 | n, *A = list(map(int, input.split())) 21 | print(partition3(A)) 22 | -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/3_maximum_value_of_an_arithmetic_expression/PlacingParentheses.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class PlacingParentheses { 4 | private static long getMaximValue(String exp) { 5 | //write your code here 6 | return 0; 7 | } 8 | 9 | private static long eval(long a, long b, char op) { 10 | if (op == '+') { 11 | return a + b; 12 | } else if (op == '-') { 13 | return a - b; 14 | } else if (op == '*') { 15 | return a * b; 16 | } else { 17 | assert false; 18 | return 0; 19 | } 20 | } 21 | 22 | public static void main(String[] args) { 23 | Scanner scanner = new Scanner(System.in); 24 | String exp = scanner.next(); 25 | System.out.println(getMaximValue(exp)); 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/3_maximum_value_of_an_arithmetic_expression/PlacingParentheses.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun getMaximValue(exp: String): Long { 4 | //write your code here 5 | return 0 6 | } 7 | 8 | fun eval(a: Long, b: Long, op: Char): Long = when (op) { 9 | '+' -> a + b 10 | '-' -> a - b 11 | '*' -> a * b 12 | else -> { 13 | assert(false) 14 | 0 15 | } 16 | } 17 | 18 | fun main(args: Array) { 19 | val scanner = Scanner(System.`in`) 20 | val exp = scanner.next() 21 | println(getMaximValue(exp)) 22 | } -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/3_maximum_value_of_an_arithmetic_expression/by_learners/placing_parentheses.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # by Andronik Ordian 3 | 4 | NUM_MAX = (2**(0.size * 8 - 2) - 1) 5 | NUM_MIN = -(2**(0.size * 8 - 2)) 6 | 7 | def evaluate(a, op, b) 8 | ops = { 9 | '+' => ->(x, y) { x + y }, 10 | '-' => ->(x, y) { x - y }, 11 | '*' => ->(x, y) { x * y } 12 | } 13 | ops[op].call(a, b) 14 | end 15 | 16 | 17 | def get_maximum_value(numbers, operations) 18 | # write your code here 19 | evaluate(2, '*', 2) 20 | end 21 | 22 | if __FILE__ == $0 23 | s = gets.chomp.bytes.to_a 24 | numbers = s.each_slice(2).map { |slice| slice.first - "0".bytes.first } 25 | operations = s.drop(1).each_slice(2).map(&:first).map(&:chr) 26 | puts get_maximum_value(numbers, operations) 27 | end 28 | -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/3_maximum_value_of_an_arithmetic_expression/placing_parentheses.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using std::vector; 7 | using std::string; 8 | using std::max; 9 | using std::min; 10 | 11 | long long eval(long long a, long long b, char op) { 12 | if (op == '*') { 13 | return a * b; 14 | } else if (op == '+') { 15 | return a + b; 16 | } else if (op == '-') { 17 | return a - b; 18 | } else { 19 | assert(0); 20 | } 21 | } 22 | 23 | long long get_maximum_value(const string &exp) { 24 | //write your code here 25 | return 0; 26 | } 27 | 28 | int main() { 29 | string s; 30 | std::cin >> s; 31 | std::cout << get_maximum_value(s) << '\n'; 32 | } 33 | -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/3_maximum_value_of_an_arithmetic_expression/placing_parentheses.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | def evalt(a, b, op): 3 | if op == "+": 4 | return a + b 5 | elif op == "-": 6 | return a - b 7 | elif op == "*": 8 | return a * b 9 | else: 10 | assert False 11 | 12 | 13 | def get_maximum_value(dataset): 14 | # write your code here 15 | return 0 16 | 17 | 18 | if __name__ == "__main__": 19 | print(get_maximum_value(input())) 20 | -------------------------------------------------------------------------------- /input/week6_dynamic_programming2/week6_dynamic_programming2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WillKoehrsen/data-structures-and-algorithms-coursera/d13b5460447d3decc095aa54b883e01d8c8a9860/input/week6_dynamic_programming2/week6_dynamic_programming2.pdf --------------------------------------------------------------------------------