├── .DS_Store ├── 3Sum.cpp ├── Aaron’s Quest IV While Moses Was Away └── Build │ ├── .editorconfig │ ├── .gitignore │ ├── Checks.js │ ├── Compress.js │ ├── Config.js │ ├── README.md │ ├── appbundle.js │ ├── config_project.js │ ├── eslint.js │ ├── exec.js │ ├── gulpish.js │ ├── gulpish_bundle.js │ ├── gulpish_tasks.js │ ├── imgproc.js │ ├── index.js │ ├── jsjam22.sublime-project │ ├── json5.js │ ├── package-lock.json │ ├── package.json │ ├── resize.js │ ├── spritesheet.js │ ├── ss1.png │ ├── ss2.png │ ├── typescript.js │ ├── uglify.js │ ├── warnmatch.js │ └── web_fsbuild.js ├── C++ ├── 3Sum.cpp ├── Arithmetic Number.cpp ├── Atm _Simulator │ ├── .gitignore │ ├── Makefile │ ├── README.md │ ├── atm.cpp │ └── atm.exe ├── BFS and DFS traversal of a graph using adjacency list.cpp ├── BotClean Stochastic ├── Bucket_sort ├── Floyd’s Cycle Detection Algorithm to find the start of the loop.cpp ├── Josephus.cpp ├── KMP_algorithm.cpp ├── Kadane.cpp ├── MaxXor.cpp ├── Maximum Length of Repeated Subarray.cpp ├── Median_of_two_sorted_arrays.cpp ├── Merge Nodes in Between Zeros ├── Palindrome Free Strings.cpp ├── PhoneBook ├── Quick_Sort_Added ├── Remove one element.cpp ├── Reverse_nodes_in_k_groups.cpp ├── Rotate_Image.cpp ├── Rotting Oranges.cpp ├── Single Number.cpp ├── Sort an array of 0s, 1s and 2s.cpp ├── Sudoku_solver.cpp ├── a.exe ├── cashflow_minimizer.cpp ├── floyds.cpp ├── heap.cpp ├── mergeInterval.cpp ├── mergeoverlappingintervals.cpp ├── mergesort.cpp ├── minimum_number_of_jumps.cpp ├── nqueens.cpp ├── spiral_matrix └── topologicalsort.cpp ├── Cpp ├── Add two Binary numbers.cpp ├── Array_As_ADT.c ├── Check_if_arrays_are_equal_or_not.cpp ├── CycleDetection_InLinkedList.cpp ├── Implementation of meerge sort │ ├── mergesort.cpp │ └── readme.md ├── Lexicographically smallest string.cpp ├── Longest valid Parentheses.cpp ├── MergeTwoBst.cpp ├── MergeTwoSortedList.cpp ├── MinimizeHeight2.cpp ├── MinimizeHeight2.exe ├── Number Of Islands.cpp ├── Quicksort │ ├── README.md │ ├── quicksort.cpp │ └── quicksort.exe ├── Report Card making System .CPP ├── Search │ ├── Binary Search.cpp │ ├── Linear Search.cpp │ ├── searching.cpp │ └── ternary_search.cpp ├── Shortest Distance in a Binary Maze.cpp ├── String Game.cpp ├── bookshop_management_system.cpp ├── countSort.cpp ├── majority.cpp ├── minesweeper_game.cpp ├── minesweeper_game.exe ├── regular expression matching.cpp └── sort012.cpp ├── HtmlGame └── CarGame.html ├── Javascript projects └── Voice operated calculator │ ├── B.jpg │ ├── Instructions.css │ ├── Instructions.html │ ├── M1.jpg │ ├── S (1).html │ ├── S.css │ ├── S.js │ ├── back.jpg │ └── debug.log ├── LICENSE.md ├── Python ├── 2048game.py ├── 21number.py ├── AudioBook.py ├── C.I_calculator.py ├── CatchTheBall.py ├── Created_tower_of_hanoi.py ├── Faulty_Calculator.py ├── Health_Management_System.py ├── Implementation of quick sort ├── Leap_Year.py ├── MergeTwoBst.py ├── Merge_K_Sorted_List.py ├── Minimize_the_heights_II.py ├── Print the Fibonacci sequence ├── Reversing_the_equation.py ├── Simple_calculator.py ├── Tower of Hanoi.py ├── Tower of Hanoi │ ├── Tower of Hanoi.md │ └── towerofhanoi.py ├── Turtle.py ├── acronym.py ├── age_calculator.py ├── analogClock.py ├── captain-shield.py ├── character_rangoli.py ├── countdowntimer.py ├── digitalclock.py ├── eggCatcher.py ├── fractalDraw.py ├── insertion_sort.py ├── number_guessing.py ├── pPrinting_matrix_in_spiral.py ├── pet.py ├── pokemon.py ├── price_email.py ├── quizGame.py ├── rangoli.py ├── roadCrossing Game.py ├── rockpaperscissorgame.py ├── snek.py ├── tictac.py └── weightcalc.py └── README.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArmanKumar21/python-cpp-html-programs-projects/4ed720d28d91dee6f10f81f8f83225e6f6ab2303/.DS_Store -------------------------------------------------------------------------------- /3Sum.cpp: -------------------------------------------------------------------------------- 1 | 3Sum problem 2 | 3 | // code 4 | 5 | #include 6 | using namespace std; 7 | 8 | void findTriplets(int arr[], int n) 9 | { 10 | bool found = false; 11 | 12 | for (int i = 0; i < n - 1; i++) { 13 | unordered_set s; 14 | for (int j = i + 1; j < n; j++) { 15 | int x = -(arr[i] + arr[j]); 16 | if (s.find(x) != s.end()) { 17 | printf("%d %d %d\n", x, arr[i], arr[j]); 18 | found = true; 19 | } 20 | else 21 | s.insert(arr[j]); 22 | } 23 | } 24 | 25 | if (found == false) 26 | cout << " No Triplet Found" << endl; 27 | } 28 | int main() 29 | { 30 | int arr[] = { 0, -1, 2, -3, 1 }; 31 | int n = sizeof(arr) / sizeof(arr[0]); 32 | findTriplets(arr, n); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/.editorconfig: -------------------------------------------------------------------------------- 1 | ; editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | 11 | [*.ts] 12 | insert_final_newline = true 13 | 14 | [*.js] 15 | insert_final_newline = true 16 | 17 | [*.json] 18 | insert_final_newline = true -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/.gitignore: -------------------------------------------------------------------------------- 1 | data_store/ 2 | artifacts/ 3 | node_modules/ 4 | logs/ 5 | ynpm-debug.log 6 | npm-debug.log 7 | build.dev/ 8 | build.prod/ 9 | .gbstate/ 10 | *.sublime-workspace 11 | Bfxr 12 | *.00? 13 | config/*.json 14 | .DS_Store -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/Checks.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const JSON5 = require('json5'); 3 | const args = require('minimist')(process.argv.slice(2)); 4 | 5 | function requireVersion(dep, required) { 6 | let ver; 7 | if (dep === 'nodejs') { 8 | ver = process.versions.node; 9 | } else { 10 | try { 11 | // eslint-disable-next-line global-require, import/no-dynamic-require 12 | ver = require(`${dep}/package.json`).version; 13 | } catch (e) { 14 | return `"${dep}": missing`; 15 | } 16 | } 17 | ver = ver.split('.').map(Number); 18 | if (ver.length !== 3) { 19 | return `"${dep}": unable to parse version for package`; 20 | } 21 | required = required.split('.').map(Number); 22 | if (ver[0] !== required[0] || ver[1] < required[1] || ver[1] === required[1] && ver[2] < required[2]) { 23 | return `"${dep}": expected ${required.join('.')}+, found ${ver.join('.')}`; 24 | } 25 | return null; 26 | } 27 | function requireVersions(versions) { 28 | let errors = []; 29 | for (let key in versions) { 30 | let err = requireVersion(key, versions[key]); 31 | if (err) { 32 | errors.push(err); 33 | } 34 | } 35 | if (errors.length) { 36 | console.error('Required dependencies missing or out of date:'); 37 | for (let ii = 0; ii < errors.length; ++ii) { 38 | console.error(` ${errors[ii]}`); 39 | } 40 | console.error('Please run `npm i` to install them.'); 41 | process.exit(-1); 42 | } 43 | } 44 | 45 | module.exports = function (filename) { 46 | if (fs.readFileSync(filename, 'utf8').includes('\r\n')) { 47 | // CRLF Line endings currently break gulp-ifdef, mess up with git diff/log/blame, and 48 | // cause unnecessary diffs when pushing builds to production servers. 49 | console.error('ERROR: Windows line endings detected'); 50 | console.error('Check your git config and make sure core.autocrlf is false:\n' + 51 | ' git config --get core.autocrlf\n' + 52 | ' git config --global --add core.autocrlf false\n' + 53 | ' (or --local if you want it on for other projects)'); 54 | process.exit(-1); 55 | } 56 | 57 | function prettyInterface() { 58 | // eslint-disable-next-line global-require 59 | const console_api = require('console-api'); 60 | console_api.setPalette(console_api.palettes.desaturated); 61 | let project_name = 'glov'; 62 | try { 63 | let pkg = JSON5.parse(fs.readFileSync('./package.json', 'utf8')); 64 | if (pkg && pkg.name) { 65 | project_name = pkg.name; 66 | } 67 | } catch (e) { 68 | // ignored, use default 69 | } 70 | console_api.setTitle(args.title || `build ${args._ || filename} | ${project_name}`); 71 | } 72 | prettyInterface(); 73 | 74 | requireVersions({ 75 | 'nodejs': '16.13.0', 76 | 'glov-build': '0.0.35', 77 | 'glov-build-browserify': '0.0.4', 78 | 'glov-build-concat': '0.0.8', 79 | 'glov-build-preresolve': '0.2.0', 80 | '@jimbly/howler': '0.0.9', 81 | '@jimbly/babel-plugin-transform-modules-simple-commonjs': '0.0.3', 82 | }); 83 | }; -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/Compress.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const JSON5 = require('json5'); 3 | const args = require('minimist')(process.argv.slice(2)); 4 | 5 | function requireVersion(dep, required) { 6 | let ver; 7 | if (dep === 'nodejs') { 8 | ver = process.versions.node; 9 | } else { 10 | try { 11 | // eslint-disable-next-line global-require, import/no-dynamic-require 12 | ver = require(`${dep}/package.json`).version; 13 | } catch (e) { 14 | return `"${dep}": missing`; 15 | } 16 | } 17 | ver = ver.split('.').map(Number); 18 | if (ver.length !== 3) { 19 | return `"${dep}": unable to parse version for package`; 20 | } 21 | required = required.split('.').map(Number); 22 | if (ver[0] !== required[0] || ver[1] < required[1] || ver[1] === required[1] && ver[2] < required[2]) { 23 | return `"${dep}": expected ${required.join('.')}+, found ${ver.join('.')}`; 24 | } 25 | return null; 26 | } 27 | function requireVersions(versions) { 28 | let errors = []; 29 | for (let key in versions) { 30 | let err = requireVersion(key, versions[key]); 31 | if (err) { 32 | errors.push(err); 33 | } 34 | } 35 | if (errors.length) { 36 | console.error('Required dependencies missing or out of date:'); 37 | for (let ii = 0; ii < errors.length; ++ii) { 38 | console.error(` ${errors[ii]}`); 39 | } 40 | console.error('Please run `npm i` to install them.'); 41 | process.exit(-1); 42 | } 43 | } 44 | 45 | module.exports = function (filename) { 46 | if (fs.readFileSync(filename, 'utf8').includes('\r\n')) { 47 | // CRLF Line endings currently break gulp-ifdef, mess up with git diff/log/blame, and 48 | // cause unnecessary diffs when pushing builds to production servers. 49 | console.error('ERROR: Windows line endings detected'); 50 | console.error('Check your git config and make sure core.autocrlf is false:\n' + 51 | ' git config --get core.autocrlf\n' + 52 | ' git config --global --add core.autocrlf false\n' + 53 | ' (or --local if you want it on for other projects)'); 54 | process.exit(-1); 55 | } 56 | 57 | function prettyInterface() { 58 | // eslint-disable-next-line global-require 59 | const console_api = require('console-api'); 60 | console_api.setPalette(console_api.palettes.desaturated); 61 | let project_name = 'glov'; 62 | try { 63 | let pkg = JSON5.parse(fs.readFileSync('./package.json', 'utf8')); 64 | if (pkg && pkg.name) { 65 | project_name = pkg.name; 66 | } 67 | } catch (e) { 68 | // ignored, use default 69 | } 70 | console_api.setTitle(args.title || `build ${args._ || filename} | ${project_name}`); 71 | } 72 | prettyInterface(); 73 | 74 | requireVersions({ 75 | 'nodejs': '16.13.0', 76 | 'glov-build': '0.0.35', 77 | 'glov-build-browserify': '0.0.4', 78 | 'glov-build-concat': '0.0.8', 79 | 'glov-build-preresolve': '0.2.0', 80 | '@jimbly/howler': '0.0.9', 81 | '@jimbly/babel-plugin-transform-modules-simple-commonjs': '0.0.3', 82 | }); 83 | }; -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/Config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | server_js_files: ['**/*.[jt]s', '!**/client/**/*'], 3 | server_static: ['**/glov/common/words/*.gkg', '**/glov/common/words/*.txt'], 4 | all_js_files: ['**/*.[jt]s', '!client/vendor/**/*'], 5 | client_js_files: [ 6 | '**/*.[jt]s', 7 | '!**/server/**/*.[jt]s', 8 | '!client/vendor/**/*.[jt]s', 9 | ], 10 | client_json_files: ['client/**/*.json', 'client/**/*.json5', '!client/vendor/**/*.json'], 11 | server_json_files: ['server/**/*.json', 'server/**/*.json5'], 12 | client_html: ['client/**/*.html'], 13 | client_html_index: ['**/client/index.html'], 14 | extra_client_html: [], 15 | client_css: ['client/**/*.css', '!client/sounds/Bfxr/**'], 16 | client_static: [ 17 | 'client/**/*.webm', 18 | 'client/**/*.mp3', 19 | 'client/**/*.wav', 20 | 'client/**/*.ogg', 21 | 'client/**/*.png', 22 | 'client/**/*.jpg', 23 | 'client/**/*.glb', 24 | 'client/**/*.ico', 25 | '!**/unused/**', 26 | '!client/sounds/Bfxr/**', 27 | // 'client/**/vendor/**', 28 | // 'client/manifest.json', 29 | ], 30 | client_vendor: ['client/**/vendor/**'], 31 | compress_files: [ 32 | 'client/**', 33 | '!**/*.png', 34 | '!**/*.jpg', 35 | '!**/*.mp3', 36 | '!**/*.ogg', 37 | '!**/*.webm', 38 | '!**/*.js.map', 39 | ], 40 | client_fsdata: [ 41 | 'client/shaders/**', 42 | 'glov/client/shaders/**', 43 | 'glov/client/models/box_textured_embed.glb', 44 | 'glov/client/words/*.txt', 45 | 'glov/common/words/*.gkg', 46 | 'glov/common/words/*.txt', 47 | ], 48 | default_defines: { 49 | PLATFORM: 'web', 50 | ENV: '', 51 | }, 52 | extra_index: [], 53 | bundles: [{ 54 | entrypoint: 'app', 55 | deps: 'app_deps', 56 | is_worker: false, 57 | do_version: 'client/app.ver.json', 58 | do_reload: true, 59 | }], 60 | extra_client_tasks: [], 61 | extra_prod_inputs: [], // Will bypass the production zip bundling, but still get in the raw production output 62 | extra_zip_inputs: [], 63 | client_intermediate_input: [ 64 | 'client_json:**', 65 | 'client_js_uglify:**', 66 | ], 67 | client_register_cbs: [], 68 | }; 69 | require('./config.project.js')(module.exports); -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/README.md: -------------------------------------------------------------------------------- 1 | Gamedev.js Jam 2022 - _RAW_ 2 | ============================ 3 | 4 | Game jam entry by Jimbly and Benjaminsen - "Aaron's Quest IV: When Moses Was Away" 5 | 6 | * Play here: [dashingstrike.com/LudumDare/JS22/](http://www.dashingstrike.com/LudumDare/JS22/) 7 | * Using [Javascript libGlov/GLOV.js framework](https://github.com/Jimbly/glovjs) -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/config_project.js: -------------------------------------------------------------------------------- 1 | module.exports = function (config) { 2 | config.extra_index = [{ 3 | name: 'crazy', 4 | defines: { 5 | PLATFORM: 'crazy', 6 | }, 7 | zip: true, 8 | }, { 9 | name: 'itch', 10 | defines: { 11 | PLATFORM: 'itch', 12 | }, 13 | zip: true, 14 | }]; 15 | }; -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/eslint.js: -------------------------------------------------------------------------------- 1 | const assert = require('assert'); 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const gb = require('glov-build'); 5 | const { callbackify } = require('glov-build'); 6 | 7 | module.exports = function (opts) { 8 | let { input, name, name_files } = opts; 9 | name = name || 'eslint'; 10 | name_files = name_files || `${name}_files`; 11 | 12 | function timestamp(fn) { 13 | return fs.statSync(fn).mtime.getTime(); 14 | } 15 | 16 | let eslint; 17 | let linter; 18 | function initLinter() { 19 | if (linter) { 20 | return; 21 | } 22 | // eslint-disable-next-line global-require 23 | const { ESLint } = require('eslint'); 24 | eslint = new ESLint(); 25 | linter = callbackify(eslint.lintText.bind(eslint)); 26 | } 27 | function eslintFilesTaskInit(next) { 28 | initLinter(); 29 | next(); 30 | } 31 | function eslintFilesTask(job, done) { 32 | let file = job.getFile(); 33 | let source_code = file.contents.toString(); 34 | linter(source_code, { 35 | filePath: path.join(job.gb.getSourceRoot(), file.relative), 36 | }, function (err, results) { 37 | if (results) { 38 | assert.equal(results.length, 1); 39 | let result = results[0]; 40 | if (result.errorCount || result.warningCount || result.messages.length) { 41 | job.out({ 42 | relative: `${file.relative}.json`, 43 | contents: JSON.stringify(results), 44 | }); 45 | } 46 | } 47 | done(err); 48 | }); 49 | } 50 | 51 | let formatter; 52 | function eslintFormatterTaskInit(next) { 53 | initLinter(); 54 | eslint.loadFormatter().then(function (result) { 55 | formatter = result; 56 | // prime it / load any other deps 57 | linter('', { filePath: path.join(gb.getSourceRoot(), 'foo.js') }, function (err, results) { 58 | if (err) { 59 | throw err; 60 | } 61 | formatter.format(results); 62 | next(); 63 | }); 64 | }); 65 | } 66 | function eslintFormatterTask(job, done) { 67 | let updated_files = job.getFilesUpdated(); 68 | let user_data = job.getUserData(); 69 | let files = user_data.files = user_data.files || {}; 70 | 71 | for (let ii = 0; ii < updated_files.length; ++ii) { 72 | let f = updated_files[ii]; 73 | if (!f.contents) { 74 | delete files[f.relative]; 75 | } else { 76 | files[f.relative] = JSON.parse(f.contents); 77 | } 78 | } 79 | 80 | let all_results = []; 81 | let keys = Object.keys(files); 82 | keys.sort(); 83 | // let error_count = 0; 84 | // let warning_count = 0; 85 | for (let ii = 0; ii < keys.length; ++ii) { 86 | let results = files[keys[ii]]; 87 | // assert.equal(results.length, 1); 88 | // let result = results[0]; 89 | // error_count += result.errorCount; 90 | // warning_count += result.warningCount; 91 | all_results = all_results.concat(results); 92 | } 93 | 94 | if (all_results.length) { 95 | let results_text = formatter.format(all_results); 96 | if (results_text) { 97 | results_text = results_text.replace(/\u2716/g, 'X'); // Replace characters not in terminal/client font 98 | job.error(results_text); 99 | } 100 | } 101 | // if (error_count) { 102 | // job.error(`${error_count} lint error${error_count===1?'':'s'}`); 103 | // } 104 | // if (warning_count) { 105 | // job.warn(`${warning_count} lint warning${warning_count===1?'':'s'}`); 106 | // } 107 | done(); 108 | } 109 | 110 | gb.task({ 111 | name: name_files, 112 | type: gb.SINGLE, 113 | async: gb.ASYNC_FORK, 114 | input, 115 | init: eslintFilesTaskInit, 116 | func: eslintFilesTask, 117 | version: [timestamp('.eslintrc.js')], 118 | }); 119 | 120 | return { 121 | type: gb.ALL, 122 | input: `${name_files}:**`, 123 | init: eslintFormatterTaskInit, 124 | func: eslintFormatterTask, 125 | async: gb.ASYNC_FORK, 126 | async_task: name_files, 127 | }; 128 | }; -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/exec.js: -------------------------------------------------------------------------------- 1 | /* eslint no-use-before-define:off */ 2 | 3 | const assert = require('assert'); 4 | const child_process = require('child_process'); 5 | const gb = require('glov-build'); 6 | 7 | const copy_opts = [ 8 | 'cwd', 'detached', 'env', 'uid', 'gid', 'shell', 'stdio', 9 | 'windowsVerbatimArguments', 'windowsHide', 10 | ]; 11 | 12 | let is_win = Boolean(process.platform.match(/^win/i)); 13 | let kill_sig = is_win ? 'SIGINT' : 'SIGHUP'; 14 | 15 | function mapGBPaths(obj) { 16 | if (!obj) { 17 | return obj; 18 | } else if (Array.isArray(obj)) { 19 | for (let ii = 0; ii < obj.length; ++ii) { 20 | obj[ii] = mapGBPaths(obj[ii]); 21 | } 22 | } else if (typeof obj === 'object') { 23 | for (let key in obj) { 24 | obj[key] = mapGBPaths(obj[key]); 25 | } 26 | } else if (typeof obj === 'string') { 27 | if (obj.match(/^[^:]{2,}:[^:]*$/)) { 28 | obj = gb.getDiskPath(obj); 29 | } 30 | } 31 | return obj; 32 | } 33 | 34 | module.exports = function exec(opts) { 35 | assert.equal(typeof opts, 'object'); 36 | assert.equal(typeof opts.cmd, 'string'); 37 | opts.args = opts.args || []; 38 | assert(Array.isArray(opts.args)); 39 | opts = mapGBPaths(opts); 40 | let spawn_opts = {}; 41 | copy_opts.forEach(function (key) { 42 | if (opts[key] !== undefined) { 43 | spawn_opts[key] = opts[key]; 44 | } 45 | }); 46 | let process_container = opts.process_container || {}; 47 | 48 | let proc; 49 | function setProc(new_proc) { 50 | process_container.proc = proc = new_proc; 51 | if (process_container.on_change) { 52 | process_container.on_change(); 53 | } 54 | } 55 | 56 | process.on('exit', function onExitCleanup() { 57 | // Doesn't seem to help 58 | if (proc && proc.exitCode !== null) { 59 | // Previous run exited 60 | setProc(null); 61 | } 62 | if (proc) { 63 | proc.kill('SIGTERM'); 64 | setProc(null); 65 | } 66 | }); 67 | 68 | return { 69 | type: gb.ALL, 70 | version: Date.now(), // always runs once per process 71 | read: false, 72 | func: function (job, done) { 73 | if (proc && proc.exitCode !== null) { 74 | // Previous run exited 75 | setProc(null); 76 | } 77 | if (proc) { 78 | job.log(`Restarting ${opts.cmd} ${opts.args.join(' ')}`); 79 | let kill_proc = proc; 80 | setProc(null); 81 | kill_proc.on('exit', startProc); 82 | kill_proc.kill(kill_sig); 83 | // Use a stronger signal after a timeout if it doesn't exit? 84 | setTimeout(function () { 85 | if (kill_proc.exitCode === null) { 86 | kill_proc.kill('SIGTERM'); 87 | } 88 | }, 2500); 89 | } else { 90 | job.log(`Starting ${opts.cmd} ${opts.args.join(' ')}`); 91 | startProc(); 92 | } 93 | 94 | function startProc() { 95 | let my_proc = child_process.spawn(opts.cmd, opts.args, spawn_opts); 96 | setProc(my_proc); 97 | function guard(fn) { 98 | return function (...args) { 99 | if (proc === my_proc) { 100 | fn(...args); 101 | } 102 | }; 103 | } 104 | 105 | let is_done = false; 106 | proc.on('close', guard(function (code) { 107 | gb[code !== 0 ? 'error' : opts.await ? 'info' : 'warn']( 108 | `Sub-process "${opts.cmd}" (PID ${proc.pid}) exited with code=${code}`); 109 | if (!is_done) { 110 | is_done = true; 111 | done(code || undefined); 112 | } 113 | setProc(null); 114 | })); 115 | proc.on('error', guard(function (err) { 116 | if (!is_done) { 117 | is_done = true; 118 | done(err); 119 | } 120 | })); 121 | if (!opts.await && proc.pid && !is_done) { 122 | // Spawned successfully - Fire done() immediately if we have a PID, 123 | // otherwise wait for the error or close events that must be coming. 124 | is_done = true; 125 | done(); 126 | } 127 | } 128 | } 129 | }; 130 | }; -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/gulpish.js: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////// 2 | // Wrapper for gulp-like stream tasks to run as glov-build tasks 3 | // Caveats: 4 | // Dependencies are not tracked, to get a task to re-process something, the 5 | // referencing source file must be re-saved. 6 | // All glov-build jobs are relative to the bucket root, regardless of where 7 | // the ** is in the glob, so some tasks may need to be adjusted (e.g. 8 | // gulp-rename will behave slightly differently) 9 | 10 | const assert = require('assert'); 11 | const path = require('path'); 12 | const { Transform, Writable } = require('stream'); 13 | const gb = require('glov-build'); 14 | const { forwardSlashes } = require('glov-build'); 15 | const Vinyl = require('vinyl'); 16 | 17 | function once(f) { 18 | let done = false; 19 | return function (...args) { 20 | if (done) { 21 | return; 22 | } 23 | f(...args); 24 | }; 25 | } 26 | 27 | module.exports = function (opts, streamfunc) { 28 | // TODO: also monkey-patch require('vinyl-fs').src to detect deps? 29 | 30 | opts = opts || {}; 31 | if (typeof opts !== 'object') { 32 | opts = { target: opts }; 33 | } 34 | let { target, sort } = opts; 35 | 36 | let out_base = ''; 37 | if (typeof target === 'string' && target.includes(':')) { 38 | // format of 'target:sub/dir' 39 | target = target.split(':'); 40 | assert.equal(target.length, 2); 41 | out_base = target[1]; 42 | target = target[0]; 43 | } 44 | 45 | function func(job, done) { 46 | done = once(done); 47 | // Creating a new stream per-file, might need something smarter? Or they should be gb.ALL tasks anyway? 48 | let source_stream = new Transform({ 49 | objectMode: true, 50 | }); 51 | let input_file = null; 52 | let task_base; 53 | if (job.getTaskType() === gb.SINGLE) { 54 | let the_file = job.getFile(); 55 | let the_file_vinyl_param = the_file.toVinyl(); 56 | task_base = the_file_vinyl_param.base; 57 | input_file = new Vinyl(the_file_vinyl_param); 58 | } else { 59 | // Grab from arbitrary, assuming they're all the same! 60 | task_base = job.getFiles()[0].toVinyl().base; 61 | } 62 | let outstream = streamfunc(source_stream, input_file); 63 | outstream.on('error', function (err) { 64 | job.error(err); 65 | // don't call done(err)? many error events might be emitted! Maybe after timeout to be safe... 66 | }); 67 | let any_written = false; 68 | let target_stream = outstream.pipe(new Writable({ 69 | objectMode: true, 70 | write: function (chunk, encoding, callback) { 71 | if (target) { 72 | // If a Vinyl object, re-map to relative to the bucket 73 | if (forwardSlashes(chunk.base).startsWith(task_base)) { 74 | chunk.base = task_base; 75 | } 76 | let out_file = { 77 | relative: path.join(out_base, chunk.relative).replace(/\\/g,'/'), 78 | contents: chunk.contents, 79 | }; 80 | //assert.equal(out_file.relative, path.relative(task_base, chunk.path).replace(/\\/g, '/')); 81 | job.out(out_file); 82 | } 83 | any_written = true; 84 | callback(); 85 | }, 86 | })); 87 | target_stream.on('finish', function (err) { 88 | if (!any_written) { 89 | job.error('No files written'); 90 | } 91 | done(err); 92 | }); 93 | if (input_file) { 94 | source_stream.push(input_file); 95 | } else { 96 | let files = job.getFiles(); 97 | if (sort) { 98 | files.sort(sort); 99 | } 100 | for (let ii = 0; ii < files.length; ++ii) { 101 | source_stream.push(new Vinyl(files[ii].toVinyl())); 102 | } 103 | } 104 | source_stream.end(); 105 | } 106 | 107 | // Override func.toString for automatic versioning 108 | func.toString = function () { 109 | return Function.prototype.toString.call(func) + streamfunc.toString(); 110 | }; 111 | 112 | let ret = { 113 | type: gb.SINGLE, 114 | func, 115 | version: [ 116 | opts, 117 | streamfunc, 118 | ], 119 | }; 120 | if (typeof target === 'string') { // allow target=true to trigger output without explicit target 121 | ret.target = target; 122 | } 123 | return ret; 124 | }; -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/gulpish_tasks.js: -------------------------------------------------------------------------------- 1 | /* eslint global-require:off */ 2 | const gulpish = require('./gulpish.js'); 3 | 4 | // example, superseded by `build/eslint.js` 5 | // unused in this project 6 | exports.eslint = function () { 7 | return gulpish(null, function (stream) { 8 | const eslint = require('gulp-eslint'); 9 | let ret = stream.pipe(eslint()) 10 | .pipe(eslint.format()); 11 | ret = ret.pipe(eslint.failAfterError()); 12 | return ret; 13 | }); 14 | }; 15 | 16 | exports.client_html_default = function (target, default_defines) { 17 | return gulpish(target, function (stream) { 18 | const ifdef = require('gulp-ifdef'); 19 | const lazypipe = require('lazypipe'); 20 | const sourcemaps = require('gulp-sourcemaps'); 21 | const useref = require('gulp-useref'); 22 | const replace = require('gulp-replace'); 23 | return stream.pipe(useref({}, lazypipe().pipe(sourcemaps.init, { loadMaps: true }))) 24 | //.on('error', log.error.bind(log, 'client_html Error')) 25 | .pipe(ifdef(default_defines, { extname: ['html'] })) 26 | .pipe(replace(/#\{([^}]+)\}/g, function (a, b) { 27 | return (b in default_defines) ? default_defines[b] : 'UKNOWN_DEFINE'; 28 | })) 29 | .pipe(sourcemaps.write('./')); // writes .map file 30 | }); 31 | }; 32 | 33 | exports.client_html_custom = function (target, elem) { 34 | return gulpish(target, function (stream) { 35 | const ifdef = require('gulp-ifdef'); 36 | const rename = require('gulp-rename'); 37 | const replace = require('gulp-replace'); 38 | return stream 39 | .pipe(ifdef(elem.defines, { extname: ['html'] })) 40 | .pipe(rename(`client/index_${elem.name}.html`)) 41 | .pipe(replace(/#\{([^}]+)\}/g, function (a, b) { 42 | return (b in elem.defines) ? elem.defines[b] : 'UKNOWN_DEFINE'; 43 | })) 44 | .pipe(replace(/[^!]+/g, function (a, b) { 45 | // already bundled in client_html_default, just export filename reference 46 | return ``; 47 | })); 48 | }); 49 | }; 50 | 51 | exports.zip = function (target, elem) { 52 | return gulpish(target, function (stream) { 53 | const gulpif = require('gulp-if'); 54 | const ignore = require('gulp-ignore'); 55 | const rename = require('gulp-rename'); 56 | const zip = require('gulp-zip'); 57 | return stream 58 | .pipe(rename(function (path) { 59 | path.dirname = path.dirname.replace(/^client[/\\]?/, ''); 60 | })) 61 | .pipe(ignore.exclude('index.html')) 62 | .pipe(ignore.exclude('*.map')) 63 | .pipe(gulpif(`index_${elem.name}.html`, rename('index.html'))) 64 | .pipe(ignore.exclude('index_*.html')) 65 | .pipe(zip(`client/${elem.name}.zip`)); 66 | }); 67 | }; 68 | 69 | // example, superseded by `build/compress.js` 70 | // unused in this project 71 | exports.compress = function (target, compress_files) { 72 | return gulpish(target, function (stream) { 73 | const gulpif = require('gulp-if'); 74 | const web_compress = require('gulp-web-compress'); 75 | return stream 76 | // skipLarger so we don't end up with orphaned old compressed files 77 | // - not strictly needed after migrating to `glov-build` though! 78 | .pipe(gulpif(compress_files, web_compress({ skipLarger: false }))); 79 | }); 80 | }; -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/imgproc.js: -------------------------------------------------------------------------------- 1 | /* eslint max-len:off */ 2 | /* 3 | To use, in config.project.js, add: 4 | const imgproc = require('./imgproc.js'); 5 | let img_proc = 'client/img/proc/*.png'; 6 | config.client_static.push(`!${img_proc}`); 7 | config.client_register_cbs.push((gb) => { 8 | config.extra_client_tasks.push('client_img_proc'); 9 | gb.task({ 10 | name: 'client_img_proc', 11 | input: img_proc, 12 | target: 'dev', 13 | ...imgproc() 14 | }); 15 | }); 16 | */ 17 | const gb = require('glov-build'); 18 | const { floor } = Math; 19 | const { PNG } = require('pngjs'); 20 | const resize = require('./resize.js'); 21 | 22 | let target_size = 16; 23 | let colorType = 6; 24 | 25 | module.exports = function () { 26 | function imgproc(job, done) { 27 | let file = job.getFile(); 28 | let out_path = file.relative.replace(/\/proc\//, '/'); 29 | job.depAdd(`${file.relative}.opt`, function (err, dep_file) { 30 | let opts = {}; 31 | if (!err && dep_file.contents) { 32 | try { 33 | opts = JSON.parse(dep_file.contents); 34 | } catch (e) { 35 | return void done(e); 36 | } 37 | } 38 | let pngin; 39 | try { 40 | pngin = PNG.sync.read(file.contents); 41 | } catch (e) { 42 | if (e.toString().indexOf('at end of stream') !== -1) { 43 | // Chrome stated adding an extra 0?! 44 | let extra = 0; 45 | while (file.contents[file.contents.length - 1 - extra] === 0) { 46 | ++extra; 47 | } 48 | try { 49 | pngin = PNG.sync.read(file.contents.slice(0, -extra)); 50 | } catch (e2) { 51 | return void done(e2); 52 | } 53 | } else { 54 | return void done(e); 55 | } 56 | } 57 | let ret; 58 | let { tile } = opts; 59 | let targetw = opts.target_size || target_size; 60 | let targeth = opts.target_size || target_size; 61 | if (tile) { 62 | let num_tx = floor(pngin.width / tile); 63 | let num_ty = floor(pngin.height / tile); 64 | ret = new PNG({ width: num_tx * targetw, height: num_ty * targeth, colorType }); 65 | // resize tile by tile 66 | for (let ty=0; ty < num_ty; ++ty) { 67 | for (let tx=0; tx < num_tx; ++tx) { 68 | let imgdata = Buffer.alloc(tile*tile*4); 69 | for (let jj = 0; jj < tile; ++jj) { 70 | for (let ii = 0; ii < tile; ++ii) { 71 | for (let kk = 0; kk < 4; ++kk) { 72 | imgdata[(jj * tile + ii) * 4 + kk] = pngin.data[((ty * tile + jj) * pngin.width + tx * tile + ii) * 4 + kk]; 73 | } 74 | } 75 | } 76 | let dest = { width: targetw, height: targeth, data: Buffer.alloc(targetw * targeth * 4) }; 77 | resize.bicubicInterpolation({ data: imgdata, width: tile, height: tile }, dest); 78 | for (let jj = 0; jj < targeth; ++jj) { 79 | for (let ii = 0; ii < targetw; ++ii) { 80 | for (let kk = 0; kk < 4; ++kk) { 81 | ret.data[((ty * targeth + jj) * ret.width + tx * targetw + ii) * 4 + kk] = dest.data[(jj * targetw + ii) * 4 + kk]; 82 | } 83 | } 84 | } 85 | } 86 | } 87 | } else { 88 | // resize all at once 89 | let dest = { width: targetw, height: targeth, data: Buffer.alloc(targetw * targeth * 4) }; 90 | resize.bicubicInterpolation({ 91 | data: pngin.data, 92 | width: pngin.width, 93 | height: pngin.height, 94 | }, dest); 95 | ret = new PNG({ width: targetw, height: targeth, colorType }); 96 | ret.data = dest.data; 97 | } 98 | let buffer = PNG.sync.write(ret); 99 | job.out({ 100 | relative: out_path, 101 | contents: buffer, 102 | }); 103 | done(); 104 | }); 105 | } 106 | return { 107 | type: gb.SINGLE, 108 | func: imgproc, 109 | }; 110 | }; -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/jsjam22.sublime-project: -------------------------------------------------------------------------------- 1 | //json5 2 | { 3 | "folders": 4 | [ 5 | { 6 | "folder_exclude_patterns": 7 | [ 8 | "node_modules", 9 | ".gbstate", 10 | "build.dev", 11 | "build.prod", 12 | "logs", 13 | "data_store", 14 | ], 15 | "file_exclude_patterns": ["jquery-*.min*", "*.00?", "*.wav", "*.mp3", "*.ogg", "package-lock.json", "*.glb"], 16 | "path": "." 17 | } 18 | ] 19 | } -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/json5.js: -------------------------------------------------------------------------------- 1 | const gb = require('glov-build'); 2 | const JSON5 = require('json5'); 3 | 4 | module.exports = function (options) { 5 | options = options || {}; 6 | options.beautify = options.beautify === undefined ? true : options.beautify; 7 | 8 | function parseJSON5(job, done) { 9 | let file = job.getFile(); 10 | let obj; 11 | try { 12 | obj = JSON5.parse(String(file.contents)); 13 | } catch (err) { 14 | return void done(err); 15 | } 16 | job.out({ 17 | relative: file.relative.replace(/\.json5$/, '.json'), 18 | contents: Buffer.from(JSON.stringify(obj, null, options.beautify ? 2 : null)), 19 | }); 20 | done(); 21 | } 22 | 23 | return { 24 | type: gb.SINGLE, 25 | func: parseJSON5, 26 | }; 27 | }; -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jsjam22", 3 | "version": "0.1.0", 4 | "description": "Template for a JavaScript game project using GLOV.js", 5 | "main": "server/index.js", 6 | "keywords": [ 7 | "template", 8 | "glov", 9 | "glovjs", 10 | "glov-build", 11 | "browserify", 12 | "babel" 13 | ], 14 | "repository": { 15 | "type": "git", 16 | "url": "git@github.com:Jimbly/jsjam22.git" 17 | }, 18 | "scripts": { 19 | "start": "nodemon -w build -w ../glov-build/ -- build default --watch", 20 | "clean": "node build clean", 21 | "build": "node build build", 22 | "prod": "node build build && node dist/game/build.prod/server/index.js --master", 23 | "lint": "node build lint" 24 | }, 25 | "author": "Jimb Esser (https://github.com/Jimbly)", 26 | "contributors": [ 27 | "Jimb Esser (https://github.com/Jimbly)" 28 | ], 29 | "license": "MIT", 30 | "dependencies": { 31 | "express": "^4.17.1", 32 | "express-static-gzip": "^2.0.5", 33 | "fs-store": "^0.3.2", 34 | "fs-store-async": "^0.3.3", 35 | "gl-mat3": "^2.0.0", 36 | "gl-mat4": "^1.2.0", 37 | "glov-async": "0.0.1", 38 | "glslang-validator-prebuilt-predownloaded": "^0.0.2", 39 | "json5": "^2.1.3", 40 | "minimist": "^1.2.5", 41 | "mkdirp": "^0.5.1", 42 | "request": "^2.88.2", 43 | "winston": "^3.2.1", 44 | "winston-daily-rotate-file": "^4.5.2", 45 | "ws": "^7.1.1" 46 | }, 47 | "devDependencies": { 48 | "@babel/core": "^7.10.2", 49 | "@babel/preset-env": "7.15.6", 50 | "@babel/preset-typescript": "^7.17.12", 51 | "@jimbly/babel-plugin-transform-modules-simple-commonjs": "0.0.3", 52 | "@jimbly/howler": "0.0.9", 53 | "@types/node": "^16.9.6", 54 | "@types/request": "^2.48.7", 55 | "@typescript-eslint/eslint-plugin": "^4.33.0", 56 | "@typescript-eslint/parser": "^4.33.0", 57 | "babel-plugin-static-fs": "^3.0.0", 58 | "babelify": "^10.0.0", 59 | "browser-sync": "^2.26.7", 60 | "console-api": "0.0.5", 61 | "eslint": "^7.32.0", 62 | "eslint-plugin-import": "^2.26.0", 63 | "glov": "file:./src/glov", 64 | "glov-build": "0.0.35", 65 | "glov-build-babel": "0.0.4", 66 | "glov-build-browserify": "0.0.6", 67 | "glov-build-concat": "0.0.9", 68 | "glov-build-preresolve": "0.2.0", 69 | "glov-build-sourcemap": "0.0.5", 70 | "gulp-if": "^3.0.0", 71 | "gulp-ifdef": "^0.2.0", 72 | "gulp-ignore": "^3.0.0", 73 | "gulp-rename": "^2.0.0", 74 | "gulp-replace": "^1.0.0", 75 | "gulp-sourcemaps": "^2.6.5", 76 | "gulp-useref": "^3.1.6", 77 | "gulp-zip": "^5.0.2", 78 | "lazypipe": "^1.0.1", 79 | "micromatch": "^4.0.2", 80 | "nodemon": "^1.19.1", 81 | "regexp-sourcemaps": "^1.0.1", 82 | "typescript": "4.4.3", 83 | "uglify-js": "^3.13.1" 84 | }, 85 | "optionalDependencies": { 86 | "bufferutil": "^4.0.1" 87 | } 88 | } -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/ss1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArmanKumar21/python-cpp-html-programs-projects/4ed720d28d91dee6f10f81f8f83225e6f6ab2303/Aaron’s Quest IV While Moses Was Away/Build/ss1.png -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/ss2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArmanKumar21/python-cpp-html-programs-projects/4ed720d28d91dee6f10f81f8f83225e6f6ab2303/Aaron’s Quest IV While Moses Was Away/Build/ss2.png -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/uglify.js: -------------------------------------------------------------------------------- 1 | const gb = require('glov-build'); 2 | const sourcemap = require('glov-build-sourcemap'); 3 | 4 | module.exports = function (opts, uglify_opts) { 5 | let uglify; 6 | return { 7 | type: gb.SINGLE, 8 | init: function (next) { 9 | uglify = require('uglify-js'); // eslint-disable-line global-require 10 | next(); 11 | }, 12 | func: function (job, done) { 13 | let file = job.getFile(); 14 | job.depReset(); 15 | sourcemap.init(job, file, function (err, map) { 16 | if (err) { 17 | return void done(err); 18 | } 19 | let uglify_options = { 20 | sourceMap: { 21 | filename: map.file, 22 | includeSources: true, 23 | content: map, 24 | }, 25 | ...uglify_opts 26 | }; 27 | let files = {}; 28 | files[file.relative] = String(file.contents); 29 | 30 | let mangled = uglify.minify(files, uglify_options); 31 | if (!mangled || mangled.error) { 32 | return void done(mangled && mangled.error || 'Uglify error'); 33 | } 34 | if (mangled.warnings) { 35 | mangled.warnings.forEach(function (warn) { 36 | job.warn(warn); 37 | }); 38 | } 39 | 40 | sourcemap.out(job, { 41 | relative: file.relative, 42 | contents: mangled.code, 43 | map: mangled.map, 44 | inline: opts.inline, 45 | }); 46 | done(); 47 | }); 48 | }, 49 | version: [ 50 | opts, 51 | uglify_opts, 52 | ], 53 | }; 54 | }; -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/warnmatch.js: -------------------------------------------------------------------------------- 1 | const assert = require('assert'); 2 | const gb = require('glov-build'); 3 | 4 | // patterns = { 'No eval': /\beval\b/ } 5 | module.exports = function warnMatch(patterns) { 6 | assert.equal(typeof patterns, 'object'); 7 | for (let key in patterns) { 8 | assert(patterns[key] instanceof RegExp || typeof patterns[key] === 'string'); 9 | } 10 | return { 11 | type: gb.SINGLE, 12 | func: function (job, done) { 13 | let file = job.getFile(); 14 | let data = file.contents.toString(); 15 | for (let key in patterns) { 16 | if (data.match(patterns[key])) { 17 | job.warn(`${file.relative}: failed ${key}`); 18 | } 19 | } 20 | done(); 21 | }, 22 | version: [ 23 | patterns, 24 | ], 25 | }; 26 | }; -------------------------------------------------------------------------------- /Aaron’s Quest IV While Moses Was Away/Build/web_fsbuild.js: -------------------------------------------------------------------------------- 1 | const assert = require('assert'); 2 | const path = require('path'); 3 | const { forwardSlashes } = require('glov-build'); 4 | const concat = require('glov-build-concat'); 5 | const JSON5 = require('json5'); 6 | 7 | const preamble = `(function () { 8 | var fs = window.glov_webfs = window.glov_webfs || {};`; 9 | const postamble = '}());'; 10 | const embed_ext = '.json'; 11 | 12 | let chars = (function () { 13 | const ESC = String.fromCharCode(27); 14 | let ret = []; 15 | for (let ii = 0; ii < 256; ++ii) { 16 | ret[ii] = String.fromCharCode(ii); 17 | } 18 | // ASCII text must encode directly 19 | // single-byte nulls 20 | ret[0] = String.fromCharCode(126); 21 | // escape our escape character and otherwise overlapped values 22 | ret[27] = `${ESC}${String.fromCharCode(27)}`; 23 | ret[126] = `${ESC}${String.fromCharCode(126)}`; 24 | // escape things not valid in Javascript strings 25 | ret[8] = '\\b'; 26 | ret[9] = '\\t'; 27 | ret[10] = '\\n'; 28 | ret[11] = '\\v'; 29 | ret[12] = '\\f'; 30 | ret[13] = '\\r'; 31 | ret['\''.charCodeAt(0)] = '\\\''; 32 | ret['\\'.charCodeAt(0)] = '\\\\'; 33 | // All other characters are fine (though many get turned into 2-byte UTF-8 strings) 34 | return ret; 35 | }()); 36 | 37 | function encodeString(buf) { 38 | let ret = []; 39 | for (let ii = 0; ii < buf.length; ++ii) { 40 | let c = buf[ii]; 41 | ret.push(chars[c]); 42 | } 43 | return ret.join(''); 44 | } 45 | 46 | function encodeObj(obj) { 47 | return JSON5.stringify(obj); 48 | } 49 | 50 | function fileFSName(opts, name) { 51 | name = forwardSlashes(name).replace('autogen/', ''); 52 | if (opts.base) { 53 | name = forwardSlashes(path.relative(opts.base, name)); 54 | } 55 | // Remap `../glov/client/shaders/foo.fp` to be just `shaders/foo.fp` 56 | let non_glov_name = name.replace(/(.*glov\/(?:client|common)\/)/, ''); 57 | if (name !== non_glov_name) { 58 | return { name: non_glov_name, priority: 1 }; 59 | } else { 60 | return { name, priority: 2 }; 61 | } 62 | } 63 | 64 | module.exports = function webfsBuild(opts) { 65 | assert(opts.output); 66 | return concat({ 67 | preamble, 68 | postamble, 69 | output: opts.output, 70 | key: 'name', 71 | proc: function (job, file, next) { 72 | let { name, priority } = fileFSName(opts, file.relative); 73 | let data = file.contents; 74 | let line; 75 | if (name.endsWith(embed_ext)) { 76 | name = name.slice(0, -embed_ext.length); 77 | line = `fs['${name}'] = ${encodeObj(JSON.parse(data))};`; 78 | } else { 79 | line = `fs['${name}'] = [${data.length},'${encodeString(data)}'];`; 80 | } 81 | next(null, { name, contents: line, priority }); 82 | }, 83 | version: [ 84 | encodeObj, 85 | encodeString, 86 | fileFSName, 87 | embed_ext, 88 | ], 89 | }); 90 | }; -------------------------------------------------------------------------------- /C++/3Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The key idea is the same as the TwoSum problem. When we fix the 1st number, the 2nd and 3rd number can be found following the same reasoning as TwoSum. 3 | 4 | The only difference is that, the TwoSum problem of LEETCODE has a unique solution. However, in ThreeSum, we have multiple duplicate solutions that can be found. Most of the OLE errors happened here because you could've ended up with a solution with so many duplicates. 5 | 6 | The naive solution for the duplicates will be using the STL methods like below : 7 | 8 | std::sort(res.begin(), res.end()); 9 | res.erase(unique(res.begin(), res.end()), res.end()); 10 | 11 | But according to my submissions, this way will cause you double your time consuming almostly. 12 | 13 | A better approach is that, to jump over the number which has been scanned, no matter it is part of some solution or not. 14 | 15 | If the three numbers formed a solution, we can safely ignore all the duplicates of them. 16 | 17 | We can do this to all the three numbers such that we can remove the duplicates. 18 | 19 | Here's my AC C++ Code: 20 | */ 21 | 22 | class Solution 23 | { 24 | public: 25 | vector> threeSum(vector &num) 26 | { 27 | vector> rs; 28 | sort(num.begin(), num.end()); 29 | int i, j, k; 30 | int n = num.size(); 31 | for (i = 0; i < n - 2; i++) 32 | { 33 | j = i + 1; 34 | k = n - 1; 35 | while (j < k) 36 | { 37 | int sum = num[i] + num[j] + num[k]; 38 | if (sum == 0) 39 | { 40 | vector tmp(3); 41 | tmp[0] = num[i]; 42 | tmp[1] = num[j]; 43 | tmp[2] = num[k]; 44 | rs.push_back(tmp); 45 | while (j < k && num[j] == tmp[1]) 46 | j++; 47 | while (j < k && num[k] == tmp[2]) 48 | k--; 49 | } 50 | else if (sum > 0) 51 | { 52 | k--; 53 | } 54 | else if (sum < 0) 55 | { 56 | j++; 57 | } 58 | } 59 | while (i + 1 < num.size() && num[i + 1] == num[i]) 60 | i++; 61 | } 62 | return rs; 63 | } 64 | }; 65 | -------------------------------------------------------------------------------- /C++/Arithmetic Number.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | #define lld long long int 5 | 6 | int inSequence(int a, int b, int c) 7 | { 8 | if (c == 0 ) 9 | { 10 | if (a != b) 11 | { 12 | return 0; 13 | } 14 | else 15 | { 16 | return 1; 17 | } 18 | } 19 | 20 | if ((b - a) % c == 0) 21 | { 22 | return 1; 23 | } 24 | else 25 | { 26 | return 0; 27 | } 28 | } 29 | 30 | int main() 31 | 32 | { 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /C++/Atm _Simulator/.gitignore: -------------------------------------------------------------------------------- 1 | .dist 2 | atm 3 | atm.o -------------------------------------------------------------------------------- /C++/Atm _Simulator/Makefile: -------------------------------------------------------------------------------- 1 | all: atm 2 | 3 | atm: atm.o 4 | g++ -Wall -o atm atm.o 5 | 6 | atm.o: 7 | g++ -Wall -c atm.cpp 8 | 9 | clean: 10 | rm -f atm *.o 11 | -------------------------------------------------------------------------------- /C++/Atm _Simulator/README.md: -------------------------------------------------------------------------------- 1 | # ATM Simulator in C++ 2 | 3 | Writing my ATM Simulator in C++ 4 | 5 | ### To run this program 6 | ```bash 7 | make 8 | ``` 9 | 10 | ### The Welcome page is like this 11 | ``` 12 | Welcome to my ATM Simulator 13 | 14 | Enter any option to be served! 15 | 16 | 1. Withdraw 17 | 2. Deposit 18 | 3. Balance 19 | 20 | ``` 21 | 22 | ### To Deposit 23 | 24 | ``` 25 | Please enter amount to deposit: 1000 26 | Thank you for depositing, new balance is: $1000. 27 | 28 | Do you want another transection? 29 | Press 1 to proceed and 2 to exit 30 | 31 | ``` 32 | 33 | ### To Withdraw 34 | 35 | ``` 36 | Please enter amount to withdraw: 90 37 | You have withdraw $90.00 and your new balance is $910.00 38 | 39 | Do you want another transection? 40 | Press 1 to proceed and 2 to exit 41 | 42 | ``` 43 | 44 | ### To check Balance 45 | 46 | ``` 47 | You bank balance is: $910.00 48 | 49 | Do you want another transection? 50 | Press 1 to proceed and 2 to exit 51 | 52 | ``` 53 | 54 | 55 | ### To Exit 56 | ``` 57 | Thanks for using our service!!! 58 | Have a nice day 59 | ``` -------------------------------------------------------------------------------- /C++/Atm _Simulator/atm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | float balance = 0; 6 | int anotherTransaction; 7 | 8 | void transaction() 9 | { 10 | int choice; 11 | cout << "\nEnter any option to be served!\n" << endl; 12 | cout << "1. Withdraw" << endl; 13 | cout << "2. Deposit" << endl; 14 | cout << "3. Balance\n" << endl; 15 | cout << ">>"; 16 | cin >> choice; 17 | int amountToWithDraw; 18 | int amountToDeposit; 19 | 20 | switch(choice) 21 | { 22 | case 1: 23 | // Withdraw 24 | cout << "\nPlease enter amount to withdraw: "; 25 | cin >> amountToWithDraw; 26 | if (amountToWithDraw > balance) 27 | { 28 | cout << "There is no insufficient funds in your account" << endl; 29 | cout << "Do you want another transaction?\nPress 1 to proceed and 2 to exit" << endl; 30 | cout << ">>"; 31 | cin >> anotherTransaction; 32 | if (anotherTransaction == 1) 33 | transaction(); 34 | } 35 | else 36 | { 37 | balance -= amountToWithDraw; 38 | cout << "You have withdrawn $" << amountToWithDraw << ".00 and you balance is $" << balance << ".00" << endl; 39 | cout << "Do you want another transaction?\nPress 1 to proceed and 2 to exit \n" << endl; 40 | cout << ">>"; 41 | cin >> anotherTransaction; 42 | if (anotherTransaction == 1) 43 | transaction(); 44 | } 45 | break; 46 | 47 | case 2: 48 | // Deposit 49 | cout << "\nPlease enter amount to deposit: "; 50 | cin >> amountToDeposit; 51 | 52 | balance += amountToDeposit; 53 | 54 | cout << "Thank you for depositing, new balance is $" << balance << ".00" << endl; 55 | cout << "Do you want another transaction?\nPress 1 to proceed and 2 to exit\n" << endl; 56 | cout << ">>"; 57 | cin >> anotherTransaction; 58 | if (anotherTransaction == 1) 59 | transaction(); 60 | break; 61 | 62 | case 3: 63 | cout << "Your bank amount balance is: " << balance << endl; 64 | cout << "Do you want another transaction?\nPress 1 to proceed and 2 to exit \n" << endl; 65 | cout << ">>"; 66 | cin >> anotherTransaction; 67 | if (anotherTransaction == 1) 68 | transaction(); 69 | break; 70 | } 71 | } 72 | 73 | int main() 74 | { 75 | transaction(); 76 | return 0; 77 | } -------------------------------------------------------------------------------- /C++/Atm _Simulator/atm.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArmanKumar21/python-cpp-html-programs-projects/4ed720d28d91dee6f10f81f8f83225e6f6ab2303/C++/Atm _Simulator/atm.exe -------------------------------------------------------------------------------- /C++/BFS and DFS traversal of a graph using adjacency list.cpp: -------------------------------------------------------------------------------- 1 | BFS and DFS traversal of a graph using adjacency list 2 | 3 | // BFS Traversal using adjacency list 4 | // Code 5 | 6 | #include 7 | using namespace std; 8 | class Graph 9 | { 10 | int V; 11 | vector> adj; 12 | public: 13 | Graph(int V); 14 | void addEdge(int v, int w); 15 | void BFS(int s); 16 | }; 17 | 18 | Graph::Graph(int V) 19 | { 20 | this->V = V; 21 | adj.resize(V); 22 | } 23 | 24 | void Graph::addEdge(int v, int w) 25 | { 26 | adj[v].push_back(w); 27 | } 28 | 29 | void Graph::BFS(int s) 30 | { 31 | vector visited; 32 | visited.resize(V,false); 33 | list queue; 34 | visited[s] = true; 35 | queue.push_back(s); 36 | 37 | while(!queue.empty()) 38 | { 39 | s = queue.front(); 40 | cout << s << " "; 41 | queue.pop_front(); 42 | for (auto adjecent: adj[s]) 43 | { 44 | if (!visited[adjecent]) 45 | { 46 | visited[adjecent] = true; 47 | queue.push_back(adjecent); 48 | } 49 | } 50 | } 51 | } 52 | 53 | int main() 54 | { 55 | Graph g(4); 56 | g.addEdge(0, 1); 57 | g.addEdge(0, 2); 58 | g.addEdge(1, 2); 59 | g.addEdge(2, 0); 60 | g.addEdge(2, 3); 61 | g.addEdge(3, 3); 62 | 63 | cout << "Following is Breadth First Traversal " 64 | << "(starting from vertex 2) \n"; 65 | g.BFS(2); 66 | return 0; 67 | } 68 | 69 | 70 | // DFS Traversal using adjacency list. 71 | // code 72 | 73 | 74 | #include 75 | using namespace std; 76 | 77 | class Graph { 78 | public: 79 | map visited; 80 | map > adj; 81 | 82 | void addEdge(int v, int w); 83 | 84 | void DFS(int v); 85 | }; 86 | 87 | void Graph::addEdge(int v, int w) 88 | { 89 | adj[v].push_back(w); 90 | } 91 | 92 | void Graph::DFS(int v) 93 | { 94 | visited[v] = true; 95 | cout << v << " "; 96 | 97 | list::iterator i; 98 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 99 | if (!visited[*i]) 100 | DFS(*i); 101 | } 102 | 103 | int main() 104 | { 105 | Graph g; 106 | g.addEdge(0, 1); 107 | g.addEdge(0, 2); 108 | g.addEdge(1, 2); 109 | g.addEdge(2, 0); 110 | g.addEdge(2, 3); 111 | g.addEdge(3, 3); 112 | 113 | cout << "Following is Depth First Traversal" 114 | " (starting from vertex 2) \n"; 115 | 116 | g.DFS(2); 117 | 118 | return 0; 119 | } 120 | 121 | 122 | 123 | -------------------------------------------------------------------------------- /C++/BotClean Stochastic: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void nextMove(int posr, int posc, vector board) { 6 | int aposr=-1; 7 | int aposc=-1; 8 | 9 | if(board[posr][posc]=='d') 10 | { 11 | cout<<"CLEAN"; 12 | } 13 | 14 | else 15 | { 16 | for(int i=0;i<5;i++) 17 | { 18 | for(int j=0;j<5;j++) 19 | { 20 | if(board[i][j]=='d') 21 | { 22 | aposr=i; 23 | aposc=j; 24 | break; 25 | } 26 | } 27 | if(aposr!=-1) 28 | { 29 | break; 30 | } 31 | } 32 | 33 | int diffr=posr-aposr; 34 | int diffc=posc-aposc; 35 | 36 | if(diffr>0) 37 | { 38 | cout<<"UP"; 39 | } 40 | 41 | else if(diffr<0) 42 | { 43 | cout<<"DOWN"; 44 | } 45 | 46 | else if(diffc>0) 47 | { 48 | cout<<"LEFT"; 49 | } 50 | 51 | else if(diffc<0) 52 | { 53 | cout<<"RIGHT"; 54 | } 55 | } 56 | 57 | return; 58 | 59 | } 60 | 61 | int main(void) { 62 | int pos[2]; 63 | vector board; 64 | cin>>pos[0]>>pos[1]; 65 | for(int i=0;i<5;i++) { 66 | string s; 67 | cin >> s; 68 | board.push_back(s); 69 | } 70 | nextMove(pos[0], pos[1], board); 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /C++/Bucket_sort: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | void bucketSort(float arr[], int n) 8 | { 9 | 10 | vector b[n]; 11 | 12 | for (int i = 0; i < n; i++) { 13 | int bi = n * arr[i]; // Index in bucket 14 | b[bi].push_back(arr[i]); 15 | } 16 | 17 | for (int i = 0; i < n; i++) 18 | sort(b[i].begin(), b[i].end()); 19 | 20 | int index = 0; 21 | for (int i = 0; i < n; i++) 22 | for (int j = 0; j < b[i].size(); j++) 23 | arr[index++] = b[i][j]; 24 | } 25 | 26 | int main() 27 | { 28 | float arr[] 29 | = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 }; 30 | int n = sizeof(arr) / sizeof(arr[0]); 31 | bucketSort(arr, n); 32 | 33 | cout << "Sorted array is \n"; 34 | for (int i = 0; i < n; i++) 35 | cout << arr[i] << " "; 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /C++/Floyd’s Cycle Detection Algorithm to find the start of the loop.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | struct ListNode { 6 | int val; 7 | ListNode *next; 8 | ListNode(int x) { 9 | val = x; 10 | next = NULL; 11 | } 12 | }; 13 | 14 | ListNode *detectCycle(ListNode *head) { 15 | ListNode *slow = head, *fast = head; 16 | while(fast and fast->next) { 17 | fast = fast->next->next; 18 | slow = slow->next; 19 | if(slow == fast) break; 20 | } 21 | if(!fast or !fast->next) return NULL; 22 | fast = head; 23 | while(slow != fast) { 24 | fast = fast->next; 25 | slow = slow->next; 26 | } 27 | return slow; 28 | } 29 | 30 | int main() { 31 | ListNode *head = new ListNode(3), *temp = head; 32 | temp->next = new ListNode(1); 33 | temp = temp->next; 34 | ListNode *cyclePoint = temp; 35 | temp->next = new ListNode(-1); 36 | temp = temp->next; 37 | temp->next = new ListNode(-10); 38 | temp = temp->next; 39 | temp->next = cyclePoint; 40 | 41 | ListNode *cycle = detectCycle(head); 42 | cout<val; 43 | cout< 2 | 3 | using namespace std; 4 | 5 | int jos(int n, int k){ 6 | if(n==1) 7 | return 0; 8 | 9 | return (jos(n-1, k) +k)%n; 10 | } 11 | 12 | int main(){ 13 | cout< 2 | using namespace std; 3 | void computeLPSArray(string pat, vector &lps) 4 | { 5 | int m = pat.size(); 6 | int len = 0; 7 | 8 | int i = 1; 9 | while (i < m) 10 | { 11 | if (pat[i] == pat[len]) 12 | { 13 | len++; 14 | lps[i] = len; 15 | i++; 16 | } 17 | else 18 | { 19 | if (len != 0) 20 | { 21 | len = lps[len - 1]; 22 | } 23 | else 24 | { 25 | lps[i] = 0; 26 | i++; 27 | } 28 | } 29 | } 30 | } 31 | void KMPSearch(string pat, string txt) 32 | { 33 | int m = pat.size(); 34 | int n = txt.size(); 35 | 36 | vector lps(m); 37 | lps[0] = 0; 38 | 39 | computeLPSArray(pat, lps); 40 | 41 | int i = 0, j = 0; 42 | while ((n - i) >= (m - j)) 43 | { 44 | if (pat[j] == txt[i]) 45 | { 46 | j++; 47 | i++; 48 | } 49 | 50 | if (j == m) 51 | { 52 | cout << "Found pattern at index: " << i - j; 53 | j = lps[j - 1]; 54 | } 55 | 56 | else if (i < n && pat[j] != txt[i]) 57 | { 58 | if (j != 0) 59 | j = lps[j - 1]; 60 | else 61 | i = i + 1; 62 | } 63 | } 64 | } 65 | 66 | int main() 67 | { 68 | string txt = "ABABDABACDABABCABAB"; 69 | string pat = "ABABCABAB"; 70 | KMPSearch(pat, txt); 71 | return 0; 72 | } -------------------------------------------------------------------------------- /C++/Kadane.cpp: -------------------------------------------------------------------------------- 1 | // Kadane's Algorithm (Maximum sum of subarray in O(N) time complexity) 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main(){ 7 | int arr[]={2,4,-8,9,10,-2,4,-20,10}; 8 | int n=9; 9 | int curr_sum=arr[0]; 10 | int max_sum=arr[0]; 11 | for(int i=1;i 2 | using namespace std; 3 | 4 | signed main() 5 | { 6 | ios_base::sync_with_stdio(0), 7 | cin.tie(0); 8 | 9 | int n; 10 | cin >> n; 11 | 12 | int arr[n + 2]; 13 | for (int i = 1; i <= n; i++) 14 | cin >> arr[i]; 15 | 16 | int res = 0; 17 | 18 | for (int mask = 0; mask < (1LL << n); mask++) 19 | { 20 | int curr = 0; 21 | for (int j = 0; j < n; j++) 22 | if (mask & (1 << j)) 23 | curr = curr ^ arr[j + 1]; 24 | 25 | res = max(res, curr); 26 | } 27 | 28 | cout << "MAX XOR is : " << res; 29 | } 30 | -------------------------------------------------------------------------------- /C++/Maximum Length of Repeated Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findLength(vector& nums1, vector& nums2) { 4 | vector> dp(nums1.size()+1, vector(nums2.size()+1)); 5 | int result =0; 6 | for(int i = 1; i <= nums1.size(); i++){ 7 | for(int j =1; j <=nums2.size(); j++){ 8 | if(nums1[i-1] == nums2[j-1]){ 9 | dp[i][j] = dp[i-1][j-1]+1; 10 | result = max(result, dp[i][j]); 11 | } 12 | else 13 | dp[i][j] = 0; 14 | } 15 | } 16 | return result; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/Median_of_two_sorted_arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 4 | int m = nums1.size(), n = nums2.size(); 5 | if(m>n)return findMedianSortedArrays(nums2,nums1);//BS on minimum size vector less comparison ++ edge case handling when partition on array 2 will point any random wrong addresss 6 | int low = 0, high = m; 7 | while(low<=high) { 8 | int cut1 = (low+high)>>1; 9 | int cut2 = ((m+n)+1)/2 - cut1; 10 | 11 | int l1 = (cut1 == 0)? INT_MIN:nums1[cut1-1]; 12 | int l2 = (cut2 == 0)? INT_MIN:nums2[cut2-1]; 13 | int r1 = (cut1 == m)? INT_MAX:nums1[cut1]; 14 | int r2 = (cut2 == n)? INT_MAX:nums2[cut2]; 15 | 16 | if(l1<=r2 && l2<=r1) { 17 | if((m+n)%2 != 0) 18 | return max(l1,l2); 19 | else 20 | return (max(l1,l2)+min(r1,r2))/2.0; 21 | } 22 | else if(l1>r2) high = cut1-1; 23 | else low = cut1+1; 24 | } 25 | return 0.0; 26 | } 27 | }; -------------------------------------------------------------------------------- /C++/Merge Nodes in Between Zeros: -------------------------------------------------------------------------------- 1 | // I took the complete problem statement from Leetcode. 2 | // link to the complete problem statement:- https://leetcode.com/problems/merge-nodes-in-between-zeros/ 3 | 4 | /** 5 | * Definition for singly-linked list. 6 | * struct ListNode { 7 | * int val; 8 | * ListNode *next; 9 | * ListNode() : val(0), next(nullptr) {} 10 | * ListNode(int x) : val(x), next(nullptr) {} 11 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | ListNode* mergeNodes(ListNode* head) { 17 | if(head->val==0)head=head->next; 18 | ListNode* prev=head; 19 | ListNode* temp=head; 20 | int sum=0; 21 | while(temp){ 22 | if(temp->val!=0){ 23 | sum=sum+temp->val; 24 | temp=temp->next; 25 | } 26 | else{ 27 | prev->val=sum; 28 | prev->next=temp->next; 29 | temp=temp->next; 30 | prev=temp; 31 | sum=0; 32 | } 33 | } 34 | return head; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /C++/Palindrome Free Strings.cpp: -------------------------------------------------------------------------------- 1 | //Author -> Samkit Jain 2 | #include 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define mod 10e8 + 7 7 | 8 | 9 | ll sort(const void *a,const void *b) //qsort(x,n,sizeof(ll),sort) 10 | { 11 | return(*(ll*)a - *(ll*)b); 12 | } 13 | ll gcd(ll a,ll b) 14 | { 15 | ll a1,b1; 16 | if(b!=0) 17 | { 18 | a1=b; 19 | b1=a%b; 20 | return gcd(a1,b1); 21 | } 22 | return a; 23 | } 24 | ll binary(ll n) 25 | { 26 | ll binary=0,temp=1; 27 | while(n>0) 28 | { 29 | binary=binary+((n%2)*temp); 30 | n=n/2; 31 | temp=temp*10; 32 | } 33 | return binary; 34 | } 35 | ll no_of_bits(ll n) 36 | { 37 | return (int)log2(n)+1; 38 | } 39 | ll prime(ll n) 40 | { 41 | if(n==0 || n==1) 42 | { 43 | return 0; 44 | } 45 | for(ll i=2;i*i<=n;i++) 46 | { 47 | if(n%i==0) 48 | {return 0;} 49 | } 50 | return 1; 51 | } 52 | 53 | bool result = false; 54 | 55 | bool check(string s) 56 | { 57 | int n = s.length(); 58 | for(ll i=0;i<=n-5;i++) 59 | { 60 | ll sure=1; 61 | for(ll l=i,r=i+4 ; l>t; 129 | for(ll test=1;test<=t;test++) 130 | { 131 | result=false; 132 | ll n; 133 | cin>>n; 134 | string s; 135 | cin>>s; 136 | 137 | fill(0,s,n); 138 | 139 | if(result) 140 | { 141 | cout<<"Case #"< 2 | using namespace std; 3 | 4 | int partition(int arr[], int start, int end) 5 | { 6 | 7 | int pivot = arr[start]; 8 | 9 | int count = 0; 10 | for (int i = start + 1; i <= end; i++) { 11 | if (arr[i] <= pivot) 12 | count++; 13 | } 14 | int pivotIndex = start + count; 15 | swap(arr[pivotIndex], arr[start]); 16 | 17 | int i = start, j = end; 18 | 19 | while (i < pivotIndex && j > pivotIndex) { 20 | 21 | while (arr[i] <= pivot) { 22 | i++; 23 | } 24 | 25 | while (arr[j] > pivot) { 26 | j--; 27 | } 28 | 29 | if (i < pivotIndex && j > pivotIndex) { 30 | swap(arr[i++], arr[j--]); 31 | } 32 | } 33 | 34 | return pivotIndex; 35 | } 36 | 37 | void quickSort(int arr[], int start, int end) 38 | { 39 | 40 | if (start >= end) 41 | return; 42 | int p = partition(arr, start, end); 43 | quickSort(arr, start, p - 1); 44 | quickSort(arr, p + 1, end); 45 | } 46 | 47 | int main() 48 | { 49 | 50 | int arr[] = { 9, 3, 4, 2, 1, 8 }; 51 | int n = 6; 52 | 53 | quickSort(arr, 0, n - 1); 54 | 55 | for (int i = 0; i < n; i++) { 56 | cout << arr[i] << " "; 57 | } 58 | 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /C++/Remove one element.cpp: -------------------------------------------------------------------------------- 1 | //Author -> Samkit Jain 2 | #include 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | 7 | int main() 8 | { 9 | ios::sync_with_stdio(0); 10 | cin.tie(0); 11 | 12 | ll t; 13 | cin>>t; 14 | for(ll test=1;test<=t;test++) 15 | { 16 | ll n; 17 | cin>>n; 18 | ll x[n+1]; 19 | ll sum1=0,sum2=0; 20 | mapm; 21 | for(ll i=1;i<=n;i++) 22 | { 23 | cin>>x[i]; 24 | sum1+=x[i]; 25 | } 26 | 27 | for(ll i=1;i>temp; 31 | sum2+=temp; 32 | m[temp]++; 33 | } 34 | 35 | ll ans = 10e9+10; 36 | for(ll i=1;i<=n;i++) 37 | { 38 | ll sum = sum1-x[i]; 39 | if(sum2-sum>0 && (sum2-sum)%(n-1)==0) 40 | { 41 | ll lol=(sum2-sum)/(n-1); 42 | ll sure=1; 43 | if(n>2) 44 | { 45 | for(ll j=1;j<=3;j++) 46 | { 47 | if(i!=j && m[x[j]+lol]==0) 48 | { 49 | sure=0; 50 | break; 51 | } 52 | } 53 | } 54 | if(sure) 55 | { 56 | ans = min(ans,(sum2-sum)/(n-1)); 57 | } 58 | } 59 | } 60 | 61 | cout<next; 7 | ListNode* curr=s; 8 | while(prev!=e) 9 | { 10 | curr->next=prev; 11 | prev=curr; 12 | curr=n; 13 | if(n!=NULL) 14 | { 15 | n=n->next; 16 | } 17 | } 18 | } 19 | ListNode* reverseKGroup(ListNode* head, int k) { 20 | if(head==NULL || head->next==NULL || k==1) 21 | { 22 | return head; 23 | } 24 | ListNode* dummynode=new ListNode(-1); 25 | dummynode->next=head; 26 | ListNode* beforestart=dummynode; 27 | ListNode* end=head; 28 | //start from ith index 29 | int i=0; 30 | while(end!=NULL) 31 | { 32 | i++; 33 | if(i%k==0) 34 | { 35 | ListNode* start=beforestart->next; 36 | ListNode* temp=end->next; //5 37 | reverse(start,end); 38 | beforestart->next=end; 39 | beforestart=start; 40 | start->next=temp; 41 | end=temp; 42 | } 43 | else 44 | { 45 | end=end->next; 46 | } 47 | } 48 | return dummynode->next; 49 | } 50 | }; -------------------------------------------------------------------------------- /C++/Rotate_Image.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | To rotate a matrix by 90 degrees we need to follow only 2 simple steps: 3 | 4 | Convert the given matrix into its transpose matrix. 5 | Take the mirror image of the transpose matrix assuming the mirror is on the right side of the matrix 6 | 7 | The resulting matrix is the required matrix. 8 | 9 | I suggest you to visualise this yourself by taking a random N*N matrix. And observe the changes after every sttep. This would help in building a better approach for similar questions. 10 | 11 | Below is the code for the proposed solution. 12 | */ 13 | 14 | void rotate(vector> &matrix) 15 | { 16 | // The idea is to take the transpose once and then taking the mirror image 17 | // The above process will result in rotating the picture by 90 degrees 18 | 19 | // Taking transpose 20 | int n = matrix.size(); 21 | for (int row = 0; row < n; ++row) 22 | { 23 | for (int col = row; col < n; ++col) 24 | { 25 | swap(matrix[row][col], matrix[col][row]); 26 | } 27 | } 28 | 29 | // Taking the mirror image with the mirror being on the right side 30 | 31 | for (int row = 0; row < n; ++row) 32 | { 33 | for (int col = 0; col < n / 2; ++col) 34 | { 35 | swap(matrix[row][col], matrix[row][n - 1 - col]); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /C++/Rotting Oranges.cpp: -------------------------------------------------------------------------------- 1 | // # Rotting Oranges 2 | 3 | #include 4 | using namespace std; 5 | 6 | int orangesRotting(int grid[3][5]) { 7 | 8 | queue> q; 9 | int row = grid.size(), col = grid[0].size(); 10 | int total = 0, rotten = 0, minutes = 0; 11 | 12 | for(int i=0 ; i=row || ny>=col || grid[nx][ny] != 1) 35 | continue; 36 | 37 | grid[nx][ny] = 2; 38 | q.push({nx,ny}); 39 | } 40 | } 41 | if(!q.empty()) 42 | minutes++; 43 | } 44 | return rotten == total ? minutes : -1; 45 | } 46 | int main(){ 47 | int R = 3, C = 5; 48 | int v[R][C] = { { 2, 1, 0, 2, 1 }, 49 | { 1, 0, 1, 2, 1 }, 50 | { 1, 0, 0, 2, 1 } }; 51 | 52 | cout << "Max time incurred: " << orangesRotting(v); 53 | 54 | return 0; 55 | } -------------------------------------------------------------------------------- /C++/Single Number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define lld long long int 4 | 5 | 6 | int singlenumber(int arr[],int n) 7 | { 8 | int ans=0;//we will use the xor property stating that xors of 2 same numbers is 0 9 | for(int i=0;i 2 | using namespace std; 3 | #define lld long long int 4 | 5 | void sort012(int arr[],int n) 6 | { 7 | int temp[3]={0};//we will apply count sort so its the storing array 8 | 9 | //traversing over the array and will increase the suitable index value 10 | for(int i=0;i0&&i0&&i0&&i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | //maximum no. of people 7 | #define N 100 8 | int graph[N][N]; 9 | string people[N]; 10 | int n; 11 | 12 | //returns index of minimum value in a[] 13 | int get_min(int a[]) 14 | { 15 | int min_ind = 0; 16 | for(int i=1; i a[max_ind]) 28 | max_ind = i; 29 | return max_ind; 30 | } 31 | 32 | // amt[p] indicates the net amount to be credited/debited 33 | // to/from person 'p' 34 | // If amt[p] is positive, then i'th person will amt[i] 35 | // If amt[p] is negative, then i'th person will give -amt[i] 36 | void min_cashflow_rec(int amt[]) 37 | { 38 | int mcr = get_max(amt), mdb = get_min(amt); 39 | if(amt[mcr] == 0 && amt[mdb] == 0) 40 | return; 41 | int minval = min(-amt[mdb], amt[mcr]); 42 | amt[mcr] -= minval; 43 | amt[mdb] += minval; 44 | cout<<"\n"<>n; 69 | //initialize the graph to 0 70 | for(int i=0; i>people[i]; 79 | } 80 | for(int i=0; i>graph[i][j]; 88 | } 89 | } 90 | min_cashflow(graph); 91 | //exit 92 | cout<<"\nPress any key to exit..."; 93 | 94 | exit(0); 95 | return 0; 96 | } 97 | -------------------------------------------------------------------------------- /C++/floyds.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int rows, number = 1; 7 | 8 | cout << "Enter number of rows: "; 9 | cin >> rows; 10 | 11 | for(int i = 1; i <= rows; i++) 12 | { 13 | for(int j = 1; j <= i; ++j) 14 | { 15 | cout << number << " "; 16 | ++number; 17 | } 18 | 19 | cout << endl; 20 | } 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /C++/heap.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | 6 | void heapify(int arr[], int n, int i) 7 | { 8 | int largest = i; 9 | int l = 2 * i + 1; 10 | int r = 2 * i + 2; 11 | 12 | if (l < n && arr[l] > arr[largest]) 13 | largest = l; 14 | 15 | if (r < n && arr[r] > arr[largest]) 16 | largest = r; 17 | 18 | 19 | if (largest != i) { 20 | swap(arr[i], arr[largest]); 21 | 22 | 23 | heapify(arr, n, largest); 24 | } 25 | } 26 | 27 | void heapSort(int arr[], int n) 28 | { 29 | 30 | for (int i = n / 2 - 1; i >= 0; i--) 31 | heapify(arr, n, i); 32 | 33 | 34 | for (int i = n - 1; i >= 0; i--) { 35 | 36 | swap(arr[0], arr[i]); 37 | 38 | 39 | heapify(arr, i, 0); 40 | } 41 | } 42 | 43 | 44 | void printArray(int arr[], int n) 45 | { 46 | for (int i = 0; i < n; ++i) 47 | cout << arr[i] << " "; 48 | cout << "\n"; 49 | } 50 | 51 | 52 | int main() 53 | { 54 | int arr[] = { 4,1,9,3,7 }; 55 | int n = sizeof(arr) / sizeof(arr[0]); 56 | 57 | heapSort(arr, n); 58 | 59 | cout << "Sorted array is \n"; 60 | printArray(arr, n); 61 | 62 | int arr[] = {10,9,8,7,6,5,4,3,2,1}; 63 | int n = sizeof(arr) / sizeof(arr[0]); 64 | 65 | heapSort(arr, n); 66 | 67 | cout << "Sorted array is \n"; 68 | printArray(arr, n); 69 | } 70 | -------------------------------------------------------------------------------- /C++/mergeInterval.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | vector> merge(vector>& intervals) 6 | { 7 | sort(intervals.begin(),intervals.end()); // sorting the vector first inorder to get intervals in line 8 | vector> result; 9 | int a1,a2,c=0;// c variable to keep the track of current smallest interval 10 | a2 = intervals[c][1]; // here a1 is for starting of the interval whereas a2 is ending of interval 11 | for (int i = 0; i < intervals.size()-1; i++) // starting linear loop 12 | { 13 | a1 = intervals[c][0];// updating a1 14 | a2 = max(intervals[i][1],a2);// updating a2 if we get even bigger limit 15 | if(intervals[i+1][0]>a2) // checking if next interval can be merged or not 16 | { 17 | c =i+1;// updating new start of interval 18 | result.push_back({a1,a2});// pushing back the last calculated interval 19 | } 20 | } 21 | a2 = max(a2,intervals[intervals.size()-1][1]);// updating a2 for last time 22 | result.push_back({intervals[c][0],a2});// pushing last interval 23 | return result; 24 | } 25 | 26 | int main() 27 | { 28 | vector> v; 29 | v.push_back({1,3}); 30 | v.push_back({0,2}); 31 | v.push_back({2,3}); 32 | v.push_back({4,6}); 33 | v.push_back({4,5}); 34 | v.push_back({5,5}); 35 | vector> result = merge(v); 36 | for (int i = 0; i < result.size(); i++)//printing merged intervals 37 | { 38 | cout< 3 | using namespace std; 4 | 5 | struct Interval { 6 | int start, end; 7 | }; 8 | 9 | 10 | bool compareInterval(Interval i1, Interval i2) 11 | { 12 | return (i1.start < i2.start); 13 | } 14 | 15 | 16 | void mergeIntervals(Interval arr[], int n) 17 | { 18 | 19 | if (n <= 0) 20 | return; 21 | 22 | // Create an empty stack of intervals 23 | stack s; 24 | 25 | // sort the intervals in increasing order of start time 26 | sort(arr, arr + n, compareInterval); 27 | 28 | // push the first interval to stack 29 | s.push(arr[0]); 30 | 31 | // Start from the next interval and merge if necessary 32 | for (int i = 1; i < n; i++) { 33 | 34 | Interval top = s.top(); 35 | 36 | if (top.end < arr[i].start) 37 | s.push(arr[i]); 38 | 39 | 40 | else if (top.end < arr[i].end) { 41 | top.end = arr[i].end; 42 | s.pop(); 43 | s.push(top); 44 | } 45 | } 46 | 47 | // Print contents of stack 48 | cout << "\n The Merged Intervals are: "; 49 | while (!s.empty()) { 50 | Interval t = s.top(); 51 | cout << "[" << t.start << "," << t.end << "] "; 52 | s.pop(); 53 | } 54 | return; 55 | } 56 | 57 | 58 | int main() 59 | { 60 | Interval arr[] 61 | = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; 62 | int n = sizeof(arr) / sizeof(arr[0]); 63 | mergeIntervals(arr, n); 64 | return 0; 65 | } 66 | //contributed by omisha 67 | 68 | -------------------------------------------------------------------------------- /C++/mergesort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void swapping(int &a, int &b) { 4 | int temp; 5 | temp = a; 6 | a = b; 7 | b = temp; 8 | } 9 | void display(int *array, int size) { 10 | for(int i = 0; i> n; 59 | int arr[n]; 60 | cout << "Enter elements:" << endl; 61 | for(int i = 0; i> arr[i]; 63 | } 64 | cout << "Array before Sorting: "; 65 | display(arr, n); 66 | mergeSort(arr, 0, n-1); 67 | cout << "Array after Sorting: "; 68 | display(arr, n); 69 | } -------------------------------------------------------------------------------- /C++/minimum_number_of_jumps.cpp: -------------------------------------------------------------------------------- 1 | int ladder = arr[0], stairs = arr[0]; 2 | int jump = 1; 3 | 4 | if(n <= 1) 5 | return 0; 6 | 7 | if(arr[0] == 0) 8 | return -1; 9 | 10 | for(int pos = 1; pos < n; pos++){ 11 | if(pos == n-1) 12 | return jump; 13 | 14 | if(ladder < arr[pos]+pos) 15 | ladder = arr[pos]+pos; 16 | 17 | stairs--; 18 | 19 | if(stairs == 0){ 20 | jump++; 21 | stairs = ladder - pos; 22 | 23 | if(stairs == 0) 24 | return -1; 25 | } 26 | } 27 | 28 | return jump; 29 | -------------------------------------------------------------------------------- /C++/nqueens.cpp: -------------------------------------------------------------------------------- 1 | /* C++ program to solve N Queen Problem using 2 | backtracking */ 3 | 4 | #include 5 | #define N 4 6 | using namespace std; 7 | 8 | /* A utility function to print solution */ 9 | void printSolution(int board[N][N]) 10 | { 11 | for (int i = 0; i < N; i++) { 12 | for (int j = 0; j < N; j++) 13 | cout << " " << board[i][j] << " "; 14 | printf("\n"); 15 | } 16 | } 17 | 18 | /* A utility function to check if a queen can 19 | be placed on board[row][col]. Note that this 20 | function is called when "col" queens are 21 | already placed in columns from 0 to col -1. 22 | So we need to check only left side for 23 | attacking queens */ 24 | bool isSafe(int board[N][N], int row, int col) 25 | { 26 | int i, j; 27 | 28 | /* Check this row on left side */ 29 | for (i = 0; i < col; i++) 30 | if (board[row][i]) 31 | return false; 32 | 33 | /* Check upper diagonal on left side */ 34 | for (i = row, j = col; i >= 0 && j >= 0; i--, j--) 35 | if (board[i][j]) 36 | return false; 37 | 38 | /* Check lower diagonal on left side */ 39 | for (i = row, j = col; j >= 0 && i < N; i++, j--) 40 | if (board[i][j]) 41 | return false; 42 | 43 | return true; 44 | } 45 | 46 | /* A recursive utility function to solve N 47 | Queen problem */ 48 | bool solveNQUtil(int board[N][N], int col) 49 | { 50 | /* base case: If all queens are placed 51 | then return true */ 52 | if (col >= N) 53 | return true; 54 | 55 | /* Consider this column and try placing 56 | this queen in all rows one by one */ 57 | for (int i = 0; i < N; i++) { 58 | /* Check if the queen can be placed on 59 | board[i][col] */ 60 | if (isSafe(board, i, col)) { 61 | /* Place this queen in board[i][col] */ 62 | board[i][col] = 1; 63 | 64 | /* recur to place rest of the queens */ 65 | if (solveNQUtil(board, col + 1)) 66 | return true; 67 | 68 | /* If placing queen in board[i][col] 69 | doesn't lead to a solution, then 70 | remove queen from board[i][col] */ 71 | board[i][col] = 0; // BACKTRACK 72 | } 73 | } 74 | 75 | /* If the queen cannot be placed in any row in 76 | this column col then return false */ 77 | return false; 78 | } 79 | 80 | /* This function solves the N Queen problem using 81 | Backtracking. It mainly uses solveNQUtil() to 82 | solve the problem. It returns false if queens 83 | cannot be placed, otherwise, return true and 84 | prints placement of queens in the form of 1s. 85 | Please note that there may be more than one 86 | solutions, this function prints one of the 87 | feasible solutions.*/ 88 | bool solveNQ() 89 | { 90 | int board[N][N] = { { 0, 0, 0, 0 }, 91 | { 0, 0, 0, 0 }, 92 | { 0, 0, 0, 0 }, 93 | { 0, 0, 0, 0 } }; 94 | 95 | if (solveNQUtil(board, 0) == false) { 96 | cout << "Solution does not exist"; 97 | return false; 98 | } 99 | 100 | printSolution(board); 101 | return true; 102 | } 103 | 104 | // driver program to test above function 105 | int main() 106 | { 107 | solveNQ(); 108 | return 0; 109 | } 110 | 111 | // This code is contributed by Aditya Kumar (adityakumar129) 112 | -------------------------------------------------------------------------------- /C++/spiral_matrix: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | vector spiralOrder(vector>& matrix) { 4 | vector ans; 5 | int n = matrix.size(); 6 | int m = matrix[0].size(); 7 | 8 | int top=0, bottom=n-1; 9 | int left=0, right=m-1; 10 | 11 | while(top<=bottom && left<=right) 12 | { 13 | for(int i=left; i<=right; i++) 14 | { 15 | ans.push_back(matrix[top][i]); 16 | } 17 | top++; 18 | 19 | for(int i=top; i<=bottom; i++) 20 | { 21 | ans.push_back(matrix[i][right]); 22 | } 23 | right--; 24 | 25 | if(top>bottom || left>right) 26 | { 27 | break; 28 | } 29 | 30 | for(int i=right; i>=left; i--) 31 | { 32 | ans.push_back(matrix[bottom][i]); 33 | } 34 | bottom--; 35 | 36 | for(int i=bottom; i>=top; i--) 37 | { 38 | ans.push_back(matrix[i][left]); 39 | } 40 | left++; 41 | } 42 | 43 | return ans; 44 | } 45 | 46 | int main() 47 | { 48 | int n,m; 49 | cin>>n>>m; 50 | 51 | vector> matrix(n, vector(m)); 52 | for(int i=0; i>matrix[i][j]; 57 | } 58 | } 59 | vector ans = spiralOrder(matrix); 60 | for(int i=0; i= 0 || j >= 0 || c == 1) 9 | { 10 | if (i >= 0) 11 | { 12 | if(a[i] == '1') c++; 13 | i--; 14 | } 15 | if (j >= 0) 16 | { 17 | if(b[j] == '1') c++; 18 | j--; 19 | } 20 | if(c == 2) 21 | { 22 | s = '0' + s; 23 | c = 1; 24 | } 25 | else if(c == 1) 26 | { 27 | s = '1' +s; 28 | c = 0; 29 | } 30 | else if(c == 0) 31 | { 32 | s = '0' + s; 33 | c = 0; 34 | } 35 | else if(c == 3) 36 | { 37 | s = '1' + s; 38 | c = 1; 39 | } 40 | } 41 | 42 | return s; 43 | 44 | 45 | 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Cpp/Array_As_ADT.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | struct myArray 4 | { 5 | int totalSize; 6 | int usedSize; 7 | int *ptr; 8 | }; 9 | void createArray(struct myArray *a, int tSize, int uSize) 10 | { 11 | // (*a).totalSize = tSize; 12 | // (*a).usedSize = uSize; 13 | // (*a).ptr = (int *) malloc(tSize*sizeof(int)); // returns a pointer to the first element of 14 | a->totalSize = tSize; 15 | a->usedSize = uSize; 16 | a->ptr = (int *)malloc(tSize * sizeof(int)); 17 | } 18 | 19 | void set(struct myArray *a){ 20 | int n; 21 | for(int i=0;iusedSize;i++){ 22 | printf("Enter elements at index %d \n",i); 23 | scanf("%d",&n); 24 | a->ptr[i]=n; 25 | } 26 | } 27 | 28 | void show(struct myArray *a) 29 | { 30 | for (int i = 0; i < a->usedSize; i++) 31 | { 32 | printf("%d\n", a->ptr[i]); 33 | } 34 | } 35 | 36 | int main() 37 | { 38 | 39 | struct myArray marks; 40 | createArray(&marks, 100, 5); // passing the address as create array takes a pointer 41 | set(&marks); 42 | show(&marks); 43 | return 0; 44 | } -------------------------------------------------------------------------------- /Cpp/Check_if_arrays_are_equal_or_not.cpp: -------------------------------------------------------------------------------- 1 | /*Hey ! Please help me with this issue. You can solve it with python or cpp then you need to make a pull request. 2 | 3 | Given two arrays A and B of equal size N, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain same set of elements, arrangements (or permutation) of elements may be different though. 4 | Note : If there are repetitions, then counts of repeated elements must also be same for two array to be equal. 5 | 6 | Example 1: 7 | 8 | Input: 9 | N = 5 10 | A[ ] = {1,2,5,4,0} 11 | B[ ] = {2,4,5,0,1} 12 | Output: 1 13 | Explanation: Both the array can be 14 | rearranged to {0,1,2,4,5} 15 | Example 2: 16 | 17 | Input: 18 | N = 3 19 | A[ ] = {1,2,5} 20 | B[ ] = {2,4,15} 21 | Output: 0 22 | Explanation: A[] and B[] have only 23 | one common value. 24 | */ 25 | 26 | #include 27 | using namespace std; 28 | 29 | int main() 30 | { 31 | int n, flag = 1; 32 | cin >> n; 33 | int arr[n], brr[n]; 34 | for (int i = 0; i < n; i++) 35 | { 36 | cin >> arr[i]; 37 | } 38 | for (int i = 0; i < n; i++) 39 | { 40 | cin >> brr[i]; 41 | } 42 | sort(arr, arr + n); 43 | sort(brr, brr + n); 44 | for (int i = 0; i < n; i++) 45 | { 46 | if (arr[i] != brr[i]) 47 | { 48 | flag = 0; 49 | break; 50 | } 51 | } 52 | if (flag) 53 | { 54 | cout << 1 << endl; 55 | return 0; 56 | } 57 | else 58 | { 59 | cout << 0 << endl; 60 | return 0; 61 | } 62 | } -------------------------------------------------------------------------------- /Cpp/CycleDetection_InLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | // ! Definition for a node of linked list 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | // ! Definition for a linked list 18 | class LinkedList 19 | { 20 | public: 21 | Node *head; 22 | LinkedList() 23 | { 24 | this->head = NULL; 25 | } 26 | void insert(int data) 27 | { 28 | Node *newNode = new Node(data); 29 | if (head == NULL) 30 | { 31 | head = newNode; 32 | return; 33 | } 34 | Node *temp = head; 35 | while (temp->next != NULL) 36 | { 37 | temp = temp->next; 38 | } 39 | temp->next = newNode; 40 | } 41 | void print() 42 | { 43 | Node *temp = head; 44 | while (temp != NULL) 45 | { 46 | cout << temp->data << " "; 47 | temp = temp->next; 48 | } 49 | cout << endl; 50 | } 51 | void isCycle() 52 | { 53 | Node *slow = head; 54 | Node *fast = head; 55 | while (fast != NULL && fast->next != NULL) 56 | { 57 | slow = slow->next; 58 | fast = fast->next->next; 59 | if (slow == fast) 60 | { 61 | cout << "Cycle is present" << endl; 62 | return; 63 | } 64 | } 65 | cout << "Cycle is not present" << endl; 66 | } 67 | }; 68 | 69 | int main() 70 | { 71 | // ! let's first create a linked linked list. 72 | LinkedList *list = new LinkedList(); 73 | list->insert(1); 74 | list->insert(2); 75 | list->insert(3); 76 | list->insert(4); 77 | list->insert(5); 78 | list->insert(6); 79 | list->insert(7); 80 | 81 | // printing the list before adding a cyle 82 | cout << "Linked list before adding a cycle" << endl; 83 | list->print(); 84 | // adding a cycle in the linked list for testing purpose. 85 | // ! for now the linked list is something like below 86 | // 1-> 2-> 3-> 4-> 5-> 6-> 7-> 4 -> 5 -> 6-> 7-> 4 and so on.. beccause of the cycle. 87 | list->head->next->next->next->next->next->next->next = list->head->next->next->next; 88 | 89 | // now we call Floyd Marshal's cycle finding algorithm to find the cycle in the linked list. 90 | list->isCycle(); 91 | return 0; 92 | } 93 | 94 | // HOW THE ALGO WORKS 95 | // Basically we have a slow pointer that moves one step at a time and a fast pointer that moves two steps at a time. 96 | // If there exists a cycle then there is a guarantee that the slow pointer and the fast pointer will meet at some point. 97 | // If they meet then exit the loop and return true. 98 | // Else if one of them becomes null then return false. -------------------------------------------------------------------------------- /Cpp/Implementation of meerge sort/mergesort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int t, n, m, i, j, parent[30005], sum[30005], ans,ans1; 5 | int a, b; 6 | int find(int x) 7 | { 8 | if (x == parent[x]) 9 | return parent[x]; 10 | else 11 | return parent[x]=find(parent[x]); 12 | } 13 | int main() 14 | { 15 | //ifstream inp; 16 | //ofstream out; 17 | ans = 2,ans1=200000000; 18 | cin>>n; 19 | assert(n<=15000); 20 | for (i = 1; i <= 2*n; i ++) 21 | { 22 | parent[i] = i; 23 | sum[i] = 1; 24 | } 25 | for (i = 0; i < n; i++) 26 | { 27 | cin>>a>>b; 28 | assert(a<=n&&a>=1); 29 | assert(b>=(n+1)&&b<=2*n); 30 | int pa = find(a); 31 | int pb = find(b); 32 | if (pa != pb) 33 | { 34 | parent[pa] = pb; 35 | sum[pb] += sum[pa]; 36 | } 37 | } 38 | for (i = 1; i <= 2*n; i ++) 39 | { 40 | if(sum[i]!=1){ 41 | int ind=find(i); 42 | ans1=min(sum[ind],ans1); 43 | } 44 | } 45 | for (i = 1; i <= 2*n; i ++) 46 | { 47 | if(sum[i]!=1){ 48 | int ind1=find(i); 49 | ans=max(sum[ind1],ans); 50 | } 51 | } 52 | cout<Merge Sort Algorithm 2 | 3 | 4 | Merge Sort is one of the most popular sorting algorithms that is based on the principle of Divide and Conquer Algorithm. 5 | 6 | Here, a problem is divided into multiple sub-problems. Each sub-problem is solved individually. Finally, sub-problems are combined to form the final solution. 7 |


8 | ![MergeSortTutorial](https://user-images.githubusercontent.com/103835667/194925985-6c8f4b28-c570-4097-844f-4075a4f3ec45.png) 9 | 10 | 11 | ***

Algorithm:

*** 12 | 13 | ``` 14 | MERGE_SORT(arr, beg, end) 15 | 16 | if beg < end 17 | set mid = (beg + end)/2 18 | MERGE_SORT(arr, beg, mid) 19 | MERGE_SORT(arr, mid + 1, end) 20 | MERGE (arr, beg, mid, end) 21 | end of if 22 | 23 | END MERGE_SORT 24 | 25 | ``` 26 |

27 | 28 | **

Merge Sort Working Process:

** 29 | 30 | 31 | Think of it as a recursive algorithm continuously splits the array in half until it cannot be further divided. This means that if the array becomes empty or has only one element left, the dividing will stop, i.e. it is the base case to stop the recursion. If the array has multiple elements, split the array into halves and recursively invoke the merge sort on each of the halves. Finally, when both halves are sorted, the merge operation is applied. Merge operation is the process of taking two smaller sorted arrays and combining them to eventually make a larger one. 32 | -------------------------------------------------------------------------------- /Cpp/Lexicographically smallest string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string lexicographicallySmallest(string s, int k) { 4 | // code here 5 | int n = s.size(); 6 | 7 | if((n&n-1) == 0) k /= 2; 8 | else k *= 2; 9 | 10 | if(k >= n) return "-1"; 11 | 12 | stack stk; 13 | string ans = ""; 14 | 15 | for(int i = 0; i < n; i++){ 16 | char ch = s[i]; 17 | 18 | while(!stk.empty() && stk.top() > ch && k > 0){ 19 | stk.pop(); 20 | k--; 21 | } 22 | 23 | stk.push(ch); 24 | } 25 | 26 | while(k > 0 && !stk.empty()){ 27 | stk.pop(); 28 | k--; 29 | } 30 | 31 | while(!stk.empty()){ 32 | ans += (char)stk.top(); 33 | stk.pop(); 34 | } 35 | 36 | reverse(ans.begin(), ans.end()); 37 | 38 | 39 | return ans; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Cpp/Longest valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution{ 3 | public: 4 | int maxLength(string s){ 5 | // code here 6 | stackst; 7 | int c=0; 8 | st.push(-1); 9 | int n=s.length(); 10 | if(n==0) return c; 11 | for(int i=0;i0) c=max(c,i-st.top()); 16 | else st.push(i); 17 | } 18 | } 19 | return c; 20 | 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Cpp/MergeTwoBst.cpp: -------------------------------------------------------------------------------- 1 | // Program to merge two BSTs 2 | 3 | #include 4 | using namespace std; 5 | 6 | // Structure of a BST Node 7 | class Node 8 | { 9 | public: 10 | int val; 11 | Node *left; 12 | Node *right; 13 | Node(int data = 0) 14 | { 15 | this->val = data; 16 | this->left = nullptr; 17 | this->right = nullptr; 18 | } 19 | }; 20 | 21 | // Function to merge two BSTs 22 | vector mergeTwoBST(Node *root1, Node *root2) 23 | { 24 | vector res; 25 | stack s1, s2; 26 | while (root1 || root2 || !s1.empty() || !s2.empty()) 27 | { 28 | while (root1) 29 | { 30 | s1.push(root1); 31 | root1 = root1->left; 32 | } 33 | while (root2) 34 | { 35 | s2.push(root2); 36 | root2 = root2->left; 37 | } 38 | if (s2.empty() || (!s1.empty() && s1.top()->val <= s2.top()->val)) 39 | { 40 | root1 = s1.top(); 41 | s1.pop(); 42 | res.push_back(root1->val); 43 | root1 = root1->right; 44 | } 45 | else 46 | { 47 | root2 = s2.top(); 48 | s2.pop(); 49 | res.push_back(root2->val); 50 | root2 = root2->right; 51 | } 52 | } 53 | return res; 54 | } 55 | 56 | // Function to build a BST from the given array; 57 | void insertBST(Node *root, vector bst) 58 | { 59 | for (int i = 1; i < bst.size(); i++) 60 | { 61 | Node *tp = root; 62 | while (tp != nullptr) 63 | { 64 | if (tp->val == bst[i]) 65 | break; 66 | else if (tp->val < bst[i]) 67 | { 68 | if (tp->right == nullptr) 69 | { 70 | tp->right = new Node(bst[i]); 71 | break; 72 | } 73 | else 74 | tp = tp->right; 75 | } 76 | else 77 | { 78 | if (tp->left == nullptr) 79 | { 80 | tp->left = new Node(bst[i]); 81 | break; 82 | } 83 | else 84 | tp = tp->left; 85 | } 86 | } 87 | } 88 | } 89 | 90 | // Function to print Inorder Transversal. 91 | void inorder(Node *root) 92 | { 93 | if (!root) 94 | return; 95 | inorder(root->left); 96 | cout << root->val << " "; 97 | inorder(root->right); 98 | } 99 | 100 | // Main Function 101 | int main() 102 | { 103 | vector bst1 = {5, 3, 6, 2, 4}, bst2 = {2, 1, 3, 7, 6}; 104 | Node *root1 = nullptr, *root2 = nullptr; 105 | root1 = new Node(bst1[0]); 106 | root2 = new Node(bst2[0]); 107 | insertBST(root1, bst1); 108 | insertBST(root2, bst2); 109 | // inorder(root1); 110 | // cout << endl; 111 | // inorder(root2); 112 | // cout << endl; 113 | vector ans = mergeTwoBST(root1, root2); 114 | for (auto it : ans) 115 | cout << it << " "; 116 | return 0; 117 | } 118 | -------------------------------------------------------------------------------- /Cpp/MinimizeHeight2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int minimize_height_II(int arr[], int n, int k) { 7 | sort(arr, arr + n); 8 | // for (int i = 0 ; i < n ; i++) cout << arr[i] << " "; 9 | // cout << endl; 10 | int curr_min = arr[0]; 11 | int curr_max = arr[n - 1]; 12 | 13 | int ans = curr_max - curr_min; 14 | // cout << curr_max << " " << curr_min << endl; 15 | // cout << ans << endl; 16 | 17 | for (int i = 1; i < n; i++) { 18 | // increase 19 | curr_min = min(arr[i] - k, arr[0]+k); 20 | // decrease 21 | curr_max = max(arr[i-1] + k, arr[n-1]-k); 22 | 23 | // cout << curr_min << " " << arr[i] << " - "<< k << " "<< arr[i]-k << endl; 24 | // cout << curr_max << " " << arr[i] << " + "<< k << " "<< arr[i]+k << endl; 25 | // cout << endl; 26 | 27 | ans = min(curr_max - curr_min, ans); 28 | 29 | } 30 | 31 | return ans; 32 | 33 | } 34 | 35 | int main() 36 | { 37 | int a[]{1, 5, 8, 10}; 38 | int n{4}; 39 | int k{2}; 40 | 41 | cout << minimize_height_II(a, n, k); 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Cpp/MinimizeHeight2.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArmanKumar21/python-cpp-html-programs-projects/4ed720d28d91dee6f10f81f8f83225e6f6ab2303/Cpp/MinimizeHeight2.exe -------------------------------------------------------------------------------- /Cpp/Number Of Islands.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector vc; 4 | int fun(int i,int j,vector> &op) 5 | { 6 | int row=op.size();int col=op[0].size(); 7 | if(i<0 || j<0 || i>=row || j>=col || op[i][j]==0) 8 | return 0; 9 | if(op[i][j]==1) 10 | { 11 | op[i][j]=0; 12 | fun(i+1,j,op); 13 | fun(i-1,j,op); 14 | fun(i,j+1,op); 15 | fun(i,j-1,op); 16 | } 17 | 18 | } 19 | vector numOfIslands(int n, int m, vector> &op) { 20 | // code here 21 | vector> grid(n,vector (m,0)); 22 | vector> gd(n,vector (m,0)); 23 | for(int i=0;iQuick Sort Algorithm 2 | 3 | 4 | Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays. A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based on which the partition is made and another array holds values greater than the pivot value. 5 | 6 | Quicksort partitions an array and then calls itself recursively twice to sort the two resulting subarrays. This algorithm is quite efficient for large-sized data sets as its average and worst-case complexity are O(n2), respectively. 7 |


8 | ![QuickSORT](https://user-images.githubusercontent.com/93043766/195206286-bafbb40d-7fd8-4e7f-a665-af82a4a48bfa.png) 9 | 10 | 11 | ***

Algorithm:

*** 12 | 13 | ``` 14 | Quick_SORT(arr, beg, end) 15 | 16 | Step 1 − Choose the highest index value has pivot 17 | Step 2 − Take two variables to point left and right of the list excluding pivot 18 | Step 3 − left points to the low index 19 | Step 4 − right points to the high 20 | Step 5 − while value at left is less than pivot move right 21 | Step 6 − while value at right is greater than pivot move left 22 | Step 7 − if both step 5 and step 6 does not match swap left and right 23 | Step 8 − if left ≥ right, the point where they met is new pivot 24 | 25 | END Quick_SORT 26 | ``` 27 |

28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Cpp/Quicksort/quicksort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Quick Sort 3 | Avg Performance O(nlogn) 4 | Worst Performance O(n^2) 5 | Space Compexity O(logn) 6 | Not Stable 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | int partition(int a[],int l,int h) 12 | { 13 | int i=l,j=h+1,pivot; 14 | pivot=a[l]; 15 | while(i<=j) 16 | { 17 | do{ 18 | i++; 19 | }while(a[i]<=pivot); 20 | do{ 21 | j--; 22 | }while(a[j]>pivot); 23 | if(i>n; 47 | int a[n]; 48 | cout<<"Enter the Array elements:- "; 49 | for(i=0;i>a[i]; 51 | quicksort(a,0,n-1); 52 | cout<<"After sorting:- "; 53 | for(i=0;i 2 | using namespace std; 3 | int binary_search(int a[],int l,int r,int key){ 4 | while(l<=r){ 5 | int m = l+(r-l)/2; 6 | if(key==a[m]) 7 | return m; 8 | else if(key>n; 20 | cout<<"Enter array elements: "; 21 | int a[n]; 22 | for (int i = 0; i < n; ++i) 23 | { 24 | cin>>a[i]; 25 | } 26 | cout<<"Enter search key: "; 27 | cin>>key; 28 | int res = binary_search(a,0,n-1,key); 29 | if(res != -1) 30 | cout< 2 | using namespace std; 3 | 4 | int LinearSearch(int *array, int size, int key) 5 | { 6 | for (int i = 0; i < size; ++i) 7 | { 8 | if (array[i]==key) 9 | { 10 | return i; 11 | } 12 | } 13 | 14 | return -1; 15 | } 16 | 17 | 18 | int main() 19 | { 20 | int size; 21 | cout<<"\nEnter the size of the Array : "; 22 | cin >> size; 23 | 24 | int array[size]; 25 | int key; 26 | 27 | //Input array 28 | cout<<"\nEnter the Array of " << size << " numbers : "; 29 | for (int i = 0; i < size; i++) 30 | { 31 | cin>>array[i]; 32 | } 33 | 34 | cout<<"\nEnter the number to be searched : "; 35 | cin>>key; 36 | 37 | int index=LinearSearch(array, size, key); 38 | if (index!=-1) 39 | { 40 | cout<<"\nNumber found at index : "< 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | char paragraph; 7 | 8 | int main() 9 | { 10 | string paragraph; 11 | cout << "Please enter your paragraph: \n"; 12 | getline (cin,paragraph); 13 | cout << "\nHello, your paragraph is:\n " << paragraph << "!\n"; 14 | cout << "\nThe size of your paragraph = " << paragraph.size() << " characters. \n\n"; 15 | 16 | if (paragraph.empty()) 17 | { 18 | cout << "\nThe paragraph is empty" << endl; 19 | } 20 | else 21 | { 22 | while (true) { 23 | string word; 24 | cout << "Please enter the word you are searching for: "; 25 | getline (cin,word); 26 | cout << "Hello, your word is " << word << "!\n"; 27 | if (paragraph.find(word) == string::npos) 28 | { 29 | cout << word << " does not exist in the sentence" << endl; 30 | } 31 | else 32 | { 33 | cout << "The word " << word << " is now found at location " << paragraph.find(word) << endl << endl; 34 | } 35 | system("pause"); 36 | } 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Cpp/Search/ternary_search.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a divide and conquer algorithm. 3 | * It does this by dividing the search space by 3 parts and 4 | * using its property (usually monotonic property) to find 5 | * the desired index. 6 | * 7 | * Time Complexity : O(log3 n) 8 | * Space Complexity : O(1) (without the array) 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | /* 15 | * The absolutePrecision can be modified to fit preference but 16 | * it is recommended to not go lower than 10 due to errors that 17 | * may occur. 18 | * 19 | * The value of _target should be decided or can be decided later 20 | * by using the variable of the function. 21 | */ 22 | 23 | #define _target 10 24 | #define absolutePrecision 10 25 | #define MAX 10000000 26 | 27 | int N = 21; 28 | int A[MAX] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,10}; 29 | 30 | /* 31 | * get_input function is to receive input from standard IO 32 | */ 33 | void get_input() 34 | { 35 | // TODO: Get input from STDIO or write input to memory as done above. 36 | } 37 | 38 | 39 | /* 40 | * This is the iterative method of the ternary search which returns the index of the element. 41 | */ 42 | int it_ternary_search(int left, int right, int A[],int target) 43 | { 44 | while (1) 45 | { 46 | if(left A[twoThird]) left = twoThird+1; 63 | else if(target < A[oneThird]) right = oneThird-1; 64 | 65 | else left = oneThird+1, right = twoThird-1; 66 | } 67 | else return -1; 68 | } 69 | } 70 | 71 | /* 72 | * This is the recursive method of the ternary search which returns the index of the element. 73 | */ 74 | int rec_ternary_search(int left, int right, int A[],int target) 75 | { 76 | if(left A[twoThird]) return rec_ternary_search(twoThird+1, right, A, target); 94 | 95 | return rec_ternary_search(oneThird+1, twoThird-1, A, target); 96 | } 97 | else return -1; 98 | } 99 | 100 | /* 101 | * ternary_search is a template function 102 | * You could either use it_ternary_search or rec_ternary_search according to preference. 103 | */ 104 | void ternary_search(int N,int A[],int target) 105 | { 106 | cout << it_ternary_search(0,N-1,A,target) << '\t'; 107 | cout << rec_ternary_search(0,N-1,A,target) << '\t'; 108 | cout << '\n'; 109 | } 110 | 111 | int main() 112 | { 113 | get_input(); 114 | ternary_search(N,A,_target); 115 | return 0; 116 | } 117 | -------------------------------------------------------------------------------- /Cpp/Shortest Distance in a Binary Maze.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int shortestPath(vector> &grid, pair source, 4 | pair d) { 5 | // code here 6 | if(grid[d.first][d.second]==0) 7 | return -1; 8 | 9 | int n=grid.size(); 10 | int m=grid[0].size(); 11 | 12 | int dp[n][m]; 13 | for(int i=0;i> q; 20 | 21 | dp[source.first][source.second]=0; 22 | 23 | q.push(source); 24 | 25 | int ans=-1; 26 | 27 | while(!q.empty()) 28 | { 29 | pair t=q.front(); 30 | q.pop(); 31 | int i=t.first; 32 | int j=t.second; 33 | 34 | 35 | if(i-1>=0&&dp[i-1][j]==-1&&grid[i-1][j]==1){ 36 | dp[i-1][j]=dp[i][j]+1; 37 | q.push({i-1,j}); 38 | } 39 | 40 | if(j-1>=0&&dp[i][j-1]==-1&&grid[i][j-1]==1){ 41 | dp[i][j-1]=dp[i][j]+1; 42 | q.push({i,j-1}); 43 | } 44 | 45 | if(i+1 Samkit Jain 2 | #include 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | #define mod 10e8 + 7 7 | 8 | 9 | ll sort(const void *a,const void *b) //qsort(x,n,sizeof(ll),sort) 10 | { 11 | return(*(ll*)a - *(ll*)b); 12 | } 13 | ll gcd(ll a,ll b) 14 | { 15 | ll a1,b1; 16 | if(b!=0) 17 | { 18 | a1=b; 19 | b1=a%b; 20 | return gcd(a1,b1); 21 | } 22 | return a; 23 | } 24 | ll binary(ll n) 25 | { 26 | ll binary=0,temp=1; 27 | while(n>0) 28 | { 29 | binary=binary+((n%2)*temp); 30 | n=n/2; 31 | temp=temp*10; 32 | } 33 | return binary; 34 | } 35 | ll no_of_bits(ll n) 36 | { 37 | return (int)log2(n)+1; 38 | } 39 | ll prime(ll n) 40 | { 41 | if(n==0 || n==1) 42 | { 43 | return 0; 44 | } 45 | for(ll i=2;i*i<=n;i++) 46 | { 47 | if(n%i==0) 48 | {return 0;} 49 | } 50 | return 1; 51 | } 52 | 53 | class DSU 54 | { 55 | public: 56 | vectorv; 57 | 58 | DSU(ll n) 59 | { 60 | v = vector(n+1); 61 | for(ll i=0;i<=n;i++) 62 | { 63 | v[i]=i; 64 | } 65 | } 66 | 67 | ll find(ll n) 68 | { 69 | if(v[n]==n) 70 | { 71 | return n; 72 | } 73 | v[n] = find(v[n]); 74 | return v[n]; 75 | } 76 | 77 | void merge(ll a,ll b) 78 | { 79 | ll a1 = find(a); 80 | ll b1 = find(b); 81 | if(a1==b1) 82 | { 83 | return; 84 | } 85 | v[b1]=a1; 86 | } 87 | }; 88 | 89 | int main() 90 | { 91 | ios::sync_with_stdio(0); 92 | cin.tie(0); 93 | 94 | ll n; 95 | cin>>n; 96 | DSU d(n); 97 | 98 | vectorv; 99 | v.push_back(0); 100 | for(int i=1;i<=n;i++) 101 | { 102 | int temp; 103 | cin>>temp; 104 | v.push_back(temp); 105 | } 106 | 107 | ll n1; 108 | cin>>n1; 109 | for(ll i=1;i<=n1;i++) 110 | { 111 | int a,b; 112 | cin>>a>>b; 113 | if(a>b) 114 | { 115 | swap(a,b); 116 | } 117 | d.merge(a,b); 118 | } 119 | 120 | vectordp(n+1,0); 121 | int ans = 0; 122 | for(ll i=0;i<=n;i++) 123 | { 124 | int parent = d.find(i); 125 | dp[parent] += v[i]; 126 | ans = max(ans,dp[parent]); 127 | } 128 | 129 | cout< 2 | using namespace std; 3 | 4 | void countSort(int arr[], int n){ 5 | map mp; 6 | for(int i=0;i>n; 22 | int arr[n]; 23 | cout<<"Enter the array: "; 24 | for(int i=0;i>arr[i]; 26 | } 27 | countSort(arr,n); 28 | cout<<"Sorted Array: "; 29 | for(int i=0;i 4 | using namespace std; 5 | 6 | // Function to find Majority element 7 | // in an array 8 | void findMajority(int arr[], int n) 9 | { 10 | int maxCount = 0; 11 | int index = -1; // sentinels 12 | for (int i = 0; i < n; i++) { 13 | int count = 0; 14 | for (int j = 0; j < n; j++) { 15 | if (arr[i] == arr[j]) 16 | count++; 17 | } 18 | 19 | // update maxCount if count of 20 | // current element is greater 21 | if (count > maxCount) { 22 | maxCount = count; 23 | index = i; 24 | } 25 | } 26 | 27 | // if maxCount is greater than n/2 28 | // return the corresponding element 29 | if (maxCount > n / 2) 30 | cout << arr[index] << endl; 31 | 32 | else 33 | cout << "No Majority Element" << endl; 34 | } 35 | 36 | // Driver code 37 | int main() 38 | { 39 | int arr[] = { 1, 1, 2, 1, 3, 5, 1 }; 40 | int n = sizeof(arr) / sizeof(arr[0]); 41 | 42 | // Function calling 43 | findMajority(arr, n); 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Cpp/minesweeper_game.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArmanKumar21/python-cpp-html-programs-projects/4ed720d28d91dee6f10f81f8f83225e6f6ab2303/Cpp/minesweeper_game.exe -------------------------------------------------------------------------------- /Cpp/regular expression matching.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Problem -> 3 | 4 | // Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: 5 | 6 | // '.' Matches any single character.​​​​ 7 | // '*' Matches zero or more of the preceding element. 8 | // The matching should cover the entire input string (not partial). 9 | // Example 1: 10 | 11 | // Input: s = "aa", p = "a" 12 | // Output: false 13 | // Explanation: "a" does not match the entire string "aa". 14 | 15 | // Example 2: 16 | 17 | // Input: s = "aa", p = "a*" 18 | // Output: true 19 | // Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". 20 | 21 | // Solution in c++ : 22 | #include 23 | using namespace std; 24 | 25 | int dp[25][35]; 26 | 27 | bool check(string &s, string &p, int i, int j, int &m, int &n) 28 | { 29 | if (i == m && j == n) 30 | return true; 31 | if (j == n) 32 | return false; 33 | if (dp[i][j] != -1) 34 | return dp[i][j]; 35 | bool valid = (i < m) && (s[i] == p[j] || p[j] == '.'); 36 | if (j + 1 < n && p[j + 1] == '*') 37 | { 38 | return dp[i][j] = check(s, p, i, j + 2, m, n) || valid && check(s, p, i + 1, j, m, n); 39 | } 40 | if (valid) 41 | { 42 | return dp[i][j] = check(s, p, i + 1, j + 1, m, n); 43 | } 44 | return dp[i][j] = false; 45 | } 46 | bool isMatch(string s, string p) 47 | { 48 | int m = s.length(), n = p.length(); 49 | memset(dp, -1, sizeof(dp)); 50 | return check(s, p, 0, 0, m, n); 51 | } 52 | 53 | int main() 54 | { 55 | string s, p; 56 | cout << "Enter 1st String(s) : "; 57 | cin >> s; 58 | cout << "\nEnter 2nd String(p) : "; 59 | cin >> p; 60 | if (isMatch(s, p)) 61 | cout << "True"; 62 | else 63 | cout << "False"; 64 | } 65 | -------------------------------------------------------------------------------- /Cpp/sort012.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void sort012(int arr[],int n) 6 | { 7 | int o=0,t=0,z=0; 8 | for(int i=0;i 2 | 3 | 4 | 5 | 11 | 12 | 13 | 133 |
134 | 135 |

Use the ACCELERATE button to stay in the air

136 |

This game is made by Rajnandan Prasad

137 | 138 | 139 | -------------------------------------------------------------------------------- /Javascript projects/Voice operated calculator/B.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArmanKumar21/python-cpp-html-programs-projects/4ed720d28d91dee6f10f81f8f83225e6f6ab2303/Javascript projects/Voice operated calculator/B.jpg -------------------------------------------------------------------------------- /Javascript projects/Voice operated calculator/Instructions.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: yellow; 3 | background-size: 100% 100%; 4 | font-family: cursive; 5 | color: red; 6 | weight: bold; 7 | } 8 | 9 | #Ob { 10 | color: purple; 11 | font-size: large; 12 | position: : relative; 13 | } 14 | 15 | #I { 16 | text-align: center; 17 | margin: 2rem auto; 18 | font-weight: bold; 19 | color: green; 20 | position: relative; 21 | font-family: Verdana, Geneva, Tahoma, sans-serif; 22 | } 23 | 24 | #O { 25 | color: indigo; 26 | font-size: 1rem; 27 | position: relative; 28 | } 29 | 30 | #C { 31 | text-align: center; 32 | font-size: 2rem; 33 | color: rgb(241, 91, 3); 34 | } 35 | 36 | .Table { 37 | text-align: center; 38 | position: relative; 39 | margin: 2rem auto; 40 | border: 0.3rem solid indigo; 41 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; 42 | } 43 | 44 | #H { 45 | font-weight: bold; 46 | } -------------------------------------------------------------------------------- /Javascript projects/Voice operated calculator/Instructions.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 |
13 |

Made with ♥ by Shreyash

14 |
15 |
Its particulary for the aged or people having trouble in reading the digits of a physical calculator.
I believe that it is particularly going to be useful for shopkeepers who can now cater more customers more efficiently
16 |
Instructions
17 |
18 |
    19 |
  1. Use mic icon for voice input
  2. 20 |
  3. Ensure a proper internet connection for experiencing speech output
  4. 21 |
  5. The Speech APIs used here are based on US-English accent. So keep that in mind while giving voice instructions.
  6. 22 | 23 |
  7. Use following keywords while defining speech operations
  8. 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 42 | 45 | 46 | 47 | 50 | 53 | 54 |
KeyWordsOperations
Plus+
Minus-
40 | Into 41 | 43 | × 44 |
48 | Divide 49 | 51 | ÷ 52 |
55 |
56 |
And Shreyash would be back with another exciting Project. 😉
57 | 58 | 59 | -------------------------------------------------------------------------------- /Javascript projects/Voice operated calculator/M1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArmanKumar21/python-cpp-html-programs-projects/4ed720d28d91dee6f10f81f8f83225e6f6ab2303/Javascript projects/Voice operated calculator/M1.jpg -------------------------------------------------------------------------------- /Javascript projects/Voice operated calculator/S (1).html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | CALOICE-Your Smart calculator 8 | 9 | 10 | 11 | 12 | 13 |
14 |
15 |
16 |

17 |
18 |
19 |

0

20 |
21 |
22 |
23 | 24 | 25 | 26 |

27 | 28 | 29 | 30 |

31 | 32 | 33 | 34 | 35 |
36 | 37 | 38 | 39 |
40 | 41 | 42 | 43 | 44 |
45 |
46 | 47 | 48 | 49 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /Javascript projects/Voice operated calculator/S.css: -------------------------------------------------------------------------------- 1 | html { 2 | font-size: 62.5%; 3 | font-family: sans-serif; 4 | background-color: white; 5 | padding: 0rem auto; 6 | } 7 | 8 | #calculator { 9 | width: 90vw; 10 | height: 90vh; 11 | background-image: url("back.jpg"); 12 | background-repeat: no-repeat; 13 | background-color: transparent; 14 | background-size: cover; 15 | top: 2rem; 16 | bottom: 2rem; 17 | left: 0rem; 18 | right: 0rem; 19 | position: relative; 20 | border-radius: 12%; 21 | border: 5px solid red; 22 | margin: 0rem auto; 23 | } 24 | 25 | #results { 26 | height: 12rem; 27 | position: relative; 28 | } 29 | 30 | #history { 31 | text-align: right; 32 | height: 2rem; 33 | margin: 0 2rem; 34 | padding-top: 2rem; 35 | font-size: 1.5rem; 36 | color: white; 37 | font-size: 2rem; 38 | position: relative; 39 | } 40 | 41 | #output { 42 | text-align: right; 43 | height: 6rem; 44 | margin: 1rem 2rem; 45 | font-size: 5rem; 46 | color: white; 47 | bottom: 0.5rem; 48 | position: relative; 49 | } 50 | 51 | #keyboard { 52 | height: 40rem auto; 53 | width: 27.5rem auto; 54 | position: relative; 55 | text-align: center; 56 | margin: 2rem; 57 | padding: 0rem; 58 | } 59 | 60 | .operator, 61 | .number, 62 | .empty { 63 | width: 5rem; 64 | height: 5rem; 65 | margin: 0.5rem; 66 | border-radius: 50%; 67 | border-width: 0; 68 | font-weight: Bold; 69 | font-size: 2.5rem; 70 | color: black; 71 | position: relative; 72 | } 73 | 74 | .number, 75 | .empty { 76 | background-color: transparent; 77 | color: white; 78 | position: relative; 79 | } 80 | 81 | .number, 82 | .operator { 83 | cursor: pointer; 84 | } 85 | 86 | .empty:hover { 87 | background-size: 125% 125%; 88 | } 89 | 90 | .operator:hover, 91 | .number:hover, 92 | { 93 | font-size: 4rem; 94 | } 95 | 96 | .operator:focus, 97 | .number:focus, 98 | .empty:focus, 99 | .mic:focus { 100 | outline: 0; 101 | } 102 | 103 | button:nth-child(4) { 104 | background-color: teal; 105 | } 106 | 107 | button:nth-child(10) { 108 | background-color: rgb(219, 114, 44); 109 | } 110 | 111 | button:nth-child(16) { 112 | background-color: rgb(143, 39, 74); 113 | } 114 | 115 | button:nth-child(21) { 116 | background-color: rgb(109, 58, 177); 117 | } 118 | 119 | button:nth-child(26) { 120 | background-color: rgb(101, 182, 207); 121 | } 122 | 123 | #tooltip { 124 | width: 12rem; 125 | height: 7rem; 126 | font-size: 1.5rem; 127 | color: black; 128 | position: absolute; 129 | text-align: left; 130 | background-color: thistle; 131 | border: 2px solid; 132 | margin-top: 2rem; 133 | border-radius: 10%; 134 | font-weight: bold; 135 | visibility: hidden; 136 | } 137 | 138 | #mic:hover #tooltip { 139 | visibility: visible; 140 | } 141 | 142 | #tooltip::before { 143 | content: ""; 144 | position: absolute; 145 | border-width: 10px; 146 | border-style: solid; 147 | border-color: transparent transparent thistle transparent; 148 | left: -0.1rem; 149 | margin-top: -2rem; 150 | } 151 | 152 | .empty { 153 | background-image: url("B.jpg"); 154 | background-size: cover; 155 | width: 5rem; 156 | height: 5rem; 157 | border-width: 0rem; 158 | margin: 0.5rem; 159 | background-color: transparent; 160 | } 161 | 162 | .mic { 163 | border-radius: 50%; 164 | width: 5rem; 165 | height: 5rem; 166 | border-width: 0rem; 167 | background-image: url("M1.jpg"); 168 | background-size: 100% 100%; 169 | background-color: transparent; 170 | margin: 0.5rem; 171 | } 172 | 173 | .record { 174 | animation: MA 1.5s infinite; 175 | } 176 | 177 | @keyframes MA { 178 | 0% { 179 | transform: scale(0.9); 180 | } 181 | 70% { 182 | transform: scale(1); 183 | box-shadow: 0 0 0 1rem rgb(251, 255, 5); 184 | } 185 | 100% { 186 | transform: scale(0.9); 187 | box-shadow: 0 0 0 0rem rgb(251, 255, 5); 188 | } 189 | } -------------------------------------------------------------------------------- /Javascript projects/Voice operated calculator/S.js: -------------------------------------------------------------------------------- 1 | alert("Made with love by Shreyash"); 2 | var O = document.getElementById("E"); 3 | var B = document.getElementById("empty"); 4 | B.onclick = function() { 5 | return location.href = "Instructions.html"; 6 | } 7 | 8 | function vibrate() { 9 | navigator.vibrate(1000); 10 | } 11 | 12 | function getHistory() { 13 | return document.getElementById("historyvalue").innerText; 14 | } 15 | 16 | function printHistory(num) { 17 | document.getElementById("historyvalue").innerText = num; 18 | } 19 | 20 | function printOutput(num) { 21 | if (num == 0) 22 | document.getElementById("output-value").innerText = num; 23 | else 24 | document.getElementById("output-value").innerText = getFormattedvalue(num); 25 | } 26 | 27 | function getOutput() { 28 | return document.getElementById("output-value").innerText; 29 | } 30 | 31 | function getFormattedvalue(num) { 32 | if (num == "-") { 33 | return ""; 34 | } 35 | var n = Number(num); 36 | var value = n.toLocaleString("en"); 37 | return value; 38 | } 39 | 40 | function RNF(num) { 41 | return Number(num.replace(/,/g, '')); 42 | } 43 | var operator = document.getElementsByClassName("operator"); 44 | for (var i = 0; i < operator.length; i++) { 45 | operator[i].addEventListener('click', function() { 46 | if (this.id == "clear") { 47 | printHistory(""); 48 | printOutput(""); 49 | } else if (this.id == "backspace") { 50 | let output = RNF(getOutput()).toString(); 51 | if (output) { 52 | output = output.substr(0, output.length - 1); 53 | printOutput(output); 54 | } 55 | } else { 56 | let output = getOutput(); 57 | let history = getHistory(); 58 | if (output == "" && history != "") { 59 | if (isNaN(history[history.length - 1])) { 60 | history = history.substr(0, history.length - 1); 61 | } 62 | } 63 | if (output != "" || history != "") { 64 | output = output == "" ? 65 | output : RNF(output); 66 | history = history + output; 67 | if (this.id == "E") { 68 | let result = eval(history); 69 | printOutput(result); 70 | printHistory(""); 71 | } else { 72 | history = history + this.id; 73 | printHistory(history); 74 | printOutput(""); 75 | } 76 | } 77 | } 78 | }); 79 | } 80 | var number = document.getElementsByClassName("number"); 81 | for (var i = 0; i < number.length; i++) { 82 | number[i].addEventListener('click', function() { 83 | var output = RNF(getOutput()); 84 | if (output != NaN) { 85 | output = output + this.id; 86 | printOutput(output); 87 | } 88 | }); 89 | } 90 | var button = document.getElementsByTagName("button"); 91 | for (let i = 0; i < button.length; i++) { 92 | try { 93 | button[i].addEventListener('click', vibrate()); 94 | throw e; 95 | } catch (e) { 96 | console.log("Tap on screen"); 97 | } 98 | } 99 | var mic = document.getElementById("mic"); 100 | mic.onclick = function() { 101 | mic.classList.add("record"); 102 | var recognition = new(window.SpeechRecognition || window.webkitSpeechRecognition || window.mozSpeechRecognition || window.msSpeechRecognition)(); 103 | recognition.lang = 'en-US'; 104 | recognition.start(); 105 | operations = { 106 | "plus": "+", 107 | "minus": "-", 108 | "multiply": "*", 109 | "divide": "/", 110 | "divided by": "/", 111 | "remainder": "%", 112 | "modulus": "%", 113 | "into": "*", 114 | "multiply by": "*", 115 | "add": "+", 116 | "slash":"/", 117 | "subtract": "-" 118 | } 119 | recognition.onresult = function(event) { 120 | var input = event.results[0][0].transcript; 121 | for (property in operations) { 122 | input = input.replace(property, operations[property]); 123 | } 124 | document.getElementById("output-value").innerText = input; 125 | setTimeout(function() { 126 | evaluate(input); 127 | }, 2000); 128 | mic.classList.remove("record"); 129 | } 130 | } 131 | 132 | function evaluate(input) { 133 | try { 134 | var result = eval(input); 135 | document.getElementById("output-value").innerText = result; 136 | } catch (e) { 137 | console.log(e); 138 | document.getElementById("output-value").innerText = ""; 139 | } 140 | } -------------------------------------------------------------------------------- /Javascript projects/Voice operated calculator/back.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ArmanKumar21/python-cpp-html-programs-projects/4ed720d28d91dee6f10f81f8f83225e6f6ab2303/Javascript projects/Voice operated calculator/back.jpg -------------------------------------------------------------------------------- /Javascript projects/Voice operated calculator/debug.log: -------------------------------------------------------------------------------- 1 | [0109/141456.636:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 2 | [0109/155721.962:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 3 | [0109/161056.340:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 4 | [0109/200259.052:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 5 | [0109/211028.857:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 6 | [0109/225534.557:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 7 | [0110/003748.033:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 8 | [0110/090018.809:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 9 | [0110/112023.049:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 10 | [0110/125748.730:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 11 | [0110/133347.747:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 12 | [0110/142638.703:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 13 | [0110/193432.865:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 14 | [0110/201038.344:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 15 | [0110/211949.704:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 16 | [0110/222903.829:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 17 | [0111/085506.566:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 18 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Aman Kumar Pandey 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Python/21number.py: -------------------------------------------------------------------------------- 1 | # Python code to play 21 Number game 2 | 3 | # returns the nearest multiple to 4 4 | def nearestMultiple(num): 5 | if num >= 4: 6 | near = num + (4 - (num % 4)) 7 | else: 8 | near = 4 9 | return near 10 | 11 | def lose1(): 12 | print ("\n\nYOU LOSE !") 13 | print("Better luck next time !") 14 | exit(0) 15 | 16 | # checks whether the numbers are consecutive 17 | def check(xyz): 18 | i = 1 19 | while i ') 33 | 34 | # player takes the first chance 35 | if chance == "F": 36 | while True: 37 | if last == 20: 38 | lose1() 39 | else: 40 | print ("\nYour Turn.") 41 | print ("\nHow many numbers do you wish to enter?") 42 | inp = int(input('> ')) 43 | 44 | if inp > 0 and inp <= 3: 45 | comp = 4 - inp 46 | else: 47 | print ("Wrong input. You are disqualified from the game.") 48 | lose1() 49 | 50 | i, j = 1, 1 51 | 52 | print ("Now enter the values") 53 | while i <= inp: 54 | a = input('> ') 55 | a = int(a) 56 | xyz.append(a) 57 | i = i + 1 58 | 59 | # store the last element of xyz. 60 | last = xyz[-1] 61 | 62 | # checks whether the input 63 | # numbers are consecutive 64 | if check(xyz) == True: 65 | if last == 21: 66 | lose1() 67 | 68 | else: 69 | #"Computer's turn." 70 | while j <= comp: 71 | xyz.append(last + j) 72 | j = j + 1 73 | print ("Order of inputs after computer's turn is: ") 74 | print (xyz) 75 | last = xyz[-1] 76 | else: 77 | print ("\nYou did not input consecutive integers.") 78 | lose1() 79 | 80 | # player takes the second chance 81 | elif chance == "S": 82 | comp = 1 83 | last = 0 84 | while last < 20: 85 | #"Computer's turn" 86 | j = 1 87 | while j <= comp: 88 | xyz.append(last + j) 89 | j = j + 1 90 | print ("Order of inputs after computer's turn is:") 91 | print (xyz) 92 | if xyz[-1] == 20: 93 | lose1() 94 | 95 | else: 96 | print ("\nYour turn.") 97 | print ("\nHow many numbers do you wish to enter?") 98 | inp = input('> ') 99 | inp = int(inp) 100 | i = 1 101 | print ("Enter your values") 102 | while i <= inp: 103 | xyz.append(int(input('> '))) 104 | i = i + 1 105 | last = xyz[-1] 106 | if check(xyz) == True: 107 | # print (xyz) 108 | near = nearestMultiple(last) 109 | comp = near - last 110 | if comp == 4: 111 | comp = 3 112 | else: 113 | comp = comp 114 | else: 115 | # if inputs are not consecutive 116 | # automatically disqualified 117 | print ("\nYou did not input consecutive integers.") 118 | # print ("You are disqualified from the game.") 119 | lose1() 120 | print ("\n\nCONGRATULATIONS !!!") 121 | print ("YOU WON !") 122 | exit(0) 123 | 124 | else: 125 | print ("wrong choice") 126 | 127 | 128 | game = True 129 | while game == True: 130 | print ("Player 2 is Computer.") 131 | print("Do you want to play the 21 number game? (Yes / No)") 132 | ans = input('> ') 133 | if ans =='Yes': 134 | start1() 135 | else: 136 | print ("Do you want quit the game?(yes / no)") 137 | nex = input('> ') 138 | if nex == "yes": 139 | print ("You are quitting the game...") 140 | exit(0) 141 | elif nex == "no": 142 | print ("Continuing...") 143 | else: 144 | print ("Wrong choice") 145 | 146 | -------------------------------------------------------------------------------- /Python/AudioBook.py: -------------------------------------------------------------------------------- 1 | import pyttsx3 2 | import PyPDF2 3 | book = open('oop.pdf', 'rb') 4 | pdfReader = PyPDF2.PdfFileReader(book) 5 | pages = pdfReader.numPages 6 | 7 | speaker = pyttsx3.init() 8 | for num in range(7, pages): 9 | page = pdfReader.getPage(num) 10 | text = page.extractText() 11 | speaker.say(text) 12 | speaker.runAndWait() 13 | -------------------------------------------------------------------------------- /Python/C.I_calculator.py: -------------------------------------------------------------------------------- 1 | # import all classes / functions from the tkinter 2 | from tkinter import * 3 | 4 | # Function for clearing the 5 | # contents of all entry boxes 6 | def clear_all() : 7 | 8 | # whole content of entry boxes is deleted 9 | principle_field.delete(0, END) 10 | rate_field.delete(0, END) 11 | time_field.delete(0, END) 12 | compound_field.delete(0, END) 13 | 14 | # set focus on the principle_field entry box 15 | principle_field.focus_set() 16 | 17 | 18 | # Function to find compound interest 19 | def calculate_ci(): 20 | 21 | # get a content from entry box 22 | principle = int(principle_field.get()) 23 | 24 | rate = float(rate_field.get()) 25 | 26 | time = int(time_field.get()) 27 | 28 | # Calculates compound interest 29 | CI = principle * (pow((1 + rate / 100), time)) 30 | 31 | # insert method inserting the 32 | # value in the text entry box. 33 | compound_field.insert(10, CI) 34 | 35 | 36 | 37 | # Driver code 38 | if __name__ == "__main__" : 39 | 40 | # Create a GUI window 41 | root = Tk() 42 | 43 | # Set the background colour of GUI window 44 | root.configure(background = 'light green') 45 | 46 | # Set the configuration of GUI window 47 | root.geometry("400x250") 48 | 49 | # set the name of tkinter GUI window 50 | root.title("Compound Interest Calculator") 51 | 52 | # Create a Principle Amount : label 53 | label1 = Label(root, text = "Principle Amount(Rs) : ", 54 | fg = 'black', bg = 'red') 55 | 56 | # Create a Rate : label 57 | label2 = Label(root, text = "Rate(%) : ", 58 | fg = 'black', bg = 'red') 59 | 60 | # Create a Time : label 61 | label3 = Label(root, text = "Time(years) : ", 62 | fg = 'black', bg = 'red') 63 | 64 | # Create a Compound Interest : label 65 | label4 = Label(root, text = "Compound Interest : ", 66 | fg = 'black', bg = 'red') 67 | 68 | # grid method is used for placing 69 | # the widgets at respective positions 70 | # in table like structure . 71 | 72 | # padx keyword argument used to set padding along x-axis . 73 | # pady keyword argument used to set padding along y-axis . 74 | label1.grid(row = 1, column = 0, padx = 10, pady = 10) 75 | label2.grid(row = 2, column = 0, padx = 10, pady = 10) 76 | label3.grid(row = 3, column = 0, padx = 10, pady = 10) 77 | label4.grid(row = 5, column = 0, padx = 10, pady = 10) 78 | 79 | # Create a entry box 80 | # for filling or typing the information. 81 | principle_field = Entry(root) 82 | rate_field = Entry(root) 83 | time_field = Entry(root) 84 | compound_field = Entry(root) 85 | 86 | # grid method is used for placing 87 | # the widgets at respective positions 88 | # in table like structure . 89 | 90 | # padx keyword argument used to set padding along x-axis . 91 | # pady keyword argument used to set padding along y-axis . 92 | principle_field.grid(row = 1, column = 1, padx = 10, pady = 10) 93 | rate_field.grid(row = 2, column = 1, padx = 10, pady = 10) 94 | time_field.grid(row = 3, column = 1, padx = 10, pady = 10) 95 | compound_field.grid(row = 5, column = 1, padx = 10, pady = 10) 96 | 97 | # Create a Submit Button and attached 98 | # to calculate_ci function 99 | button1 = Button(root, text = "Submit", bg = "red", 100 | fg = "black", command = calculate_ci) 101 | 102 | # Create a Clear Button and attached 103 | # to clear_all function 104 | button2 = Button(root, text = "Clear", bg = "red", 105 | fg = "black", command = clear_all) 106 | 107 | button1.grid(row = 4, column = 1, pady = 10) 108 | button2.grid(row = 6, column = 1, pady = 10) 109 | 110 | # Start the GUI 111 | root.mainloop() 112 | 113 | -------------------------------------------------------------------------------- /Python/CatchTheBall.py: -------------------------------------------------------------------------------- 1 | from itertools import cycle 2 | from random import randrange 3 | from tkinter import Canvas, Tk, messagebox, font 4 | 5 | canvas_width = 800 6 | canvas_height = 400 7 | 8 | root = Tk() 9 | root.title("Catch the ball") 10 | c = Canvas(root, width=canvas_width, height=canvas_height, background="light sky blue") 11 | c.create_rectangle(-5, canvas_height-100, canvas_width+5, canvas_height+5, fill="brown", width=0) 12 | c.create_oval(-80, -80, 120, 120, fill='orange', width=0) 13 | c.pack() 14 | 15 | color_cycle = cycle(["light blue", "light green", "light pink", "light yellow", "light cyan"]) 16 | egg_width = 55 17 | egg_height = 65 18 | egg_score = 10 19 | egg_speed = 600 20 | egg_interval = 4000 21 | difficulty = 0.95 22 | catcher_color = "orange" 23 | catcher_width = 100 24 | catcher_height = 100 25 | catcher_startx = canvas_width / 2 - catcher_width / 2 26 | catcher_starty = canvas_height - catcher_height - 20 27 | catcher_startx2 = catcher_startx + catcher_width 28 | catcher_starty2 = catcher_starty + catcher_height 29 | 30 | catcher = c.create_arc(catcher_startx, catcher_starty, catcher_startx2, catcher_starty2, start=200, extent=140, style="arc", outline=catcher_color, width=3) 31 | game_font = font.nametofont("TkFixedFont") 32 | game_font.config(size=18) 33 | 34 | 35 | score = 0 36 | score_text = c.create_text(10, 10, anchor="nw", font=game_font, fill="darkblue", text="Score: "+ str(score)) 37 | 38 | lives_remaining = 3 39 | lives_text = c.create_text(canvas_width-10, 10, anchor="ne", font=game_font, fill="darkblue", text="Lives: "+ str(lives_remaining)) 40 | 41 | eggs = [] 42 | 43 | def create_egg(): 44 | x = randrange(10, 740) 45 | y = 40 46 | new_egg = c.create_oval(x, y, x+egg_width, y+egg_height, fill=next(color_cycle), width=0) 47 | eggs.append(new_egg) 48 | root.after(egg_interval, create_egg) 49 | 50 | def move_eggs(): 51 | for egg in eggs: 52 | (eggx, eggy, eggx2, eggy2) = c.coords(egg) 53 | c.move(egg, 0, 10) 54 | if eggy2 > canvas_height: 55 | egg_dropped(egg) 56 | root.after(egg_speed, move_eggs) 57 | 58 | def egg_dropped(egg): 59 | eggs.remove(egg) 60 | c.delete(egg) 61 | lose_a_life() 62 | if lives_remaining == 0: 63 | messagebox.showinfo("Game Over!", "Final Score: "+ str(score)) 64 | root.destroy() 65 | 66 | def lose_a_life(): 67 | global lives_remaining 68 | lives_remaining -= 1 69 | c.itemconfigure(lives_text, text="Lives: "+ str(lives_remaining)) 70 | 71 | def check_catch(): 72 | (catcherx, catchery, catcherx2, catchery2) = c.coords(catcher) 73 | for egg in eggs: 74 | (eggx, eggy, eggx2, eggy2) = c.coords(egg) 75 | if catcherx < eggx and eggx2 < catcherx2 and catchery2 - eggy2 < 40: 76 | eggs.remove(egg) 77 | c.delete(egg) 78 | increase_score(egg_score) 79 | root.after(100, check_catch) 80 | 81 | def increase_score(points): 82 | global score, egg_speed, egg_interval 83 | score += points 84 | egg_speed = int(egg_speed * difficulty) 85 | egg_interval = int(egg_interval * difficulty) 86 | c.itemconfigure(score_text, text="Score: "+ str(score)) 87 | 88 | def move_left(event): 89 | (x1, y1, x2, y2) = c.coords(catcher) 90 | if x1 > 0: 91 | c.move(catcher, -10, 0) 92 | 93 | def move_right(event): 94 | (x1, y1, x2, y2) = c.coords(catcher) 95 | if x2 < canvas_width: 96 | c.move(catcher, 10, 0) 97 | 98 | c.bind("", move_left) 99 | c.bind("", move_right) 100 | c.focus_set() 101 | root.after(1000, create_egg) 102 | root.after(1000, move_eggs) 103 | root.after(1000, check_catch) 104 | root.mainloop() 105 | 106 | -------------------------------------------------------------------------------- /Python/Created_tower_of_hanoi.py: -------------------------------------------------------------------------------- 1 | # tower of hanoi 2 | def TowerOfHanoi(n , from_rod, to_rod, aux_rod): 3 | if n == 1: 4 | print ("Move disk 1 from rod",from_rod,"to rod",to_rod) 5 | return 6 | TowerOfHanoi(n-1, from_rod, aux_rod, to_rod) 7 | print ("Move disk",n,"from rod",from_rod,"to rod",to_rod) 8 | TowerOfHanoi(n-1, aux_rod, to_rod, from_rod) 9 | # main 10 | n = 3 11 | TowerOfHanoi(n, 'A', 'C', 'B') 12 | # A, B, C are the rod 13 | print ("Sorted array is:") 14 | for i in range(n): 15 | print (arr[i],end=" ") 16 | -------------------------------------------------------------------------------- /Python/Faulty_Calculator.py: -------------------------------------------------------------------------------- 1 | print("enter the first number") 2 | num1=int(input()) 3 | print("enter the second number") 4 | num2=int(input()) 5 | print("what do you want to perform?\n'+'for addition\n'-' for subtraction\n'*' for multiplication\n'/' for division") 6 | operator=input("enter operator:") 7 | if num1==56 and num2==9 and operator=='+': 8 | print("77") 9 | elif operator=='+': 10 | print(num1+num2) 11 | elif num1==45 and num2==3 and operator=='*': 12 | print("555") 13 | elif operator=='*': 14 | print(num1*num2) 15 | elif num1==56 and num2==6 and operator=='/': 16 | print("4") 17 | elif operator=='/': 18 | print(num1/num2) 19 | elif operator=='-': 20 | print(num1-num2) 21 | -------------------------------------------------------------------------------- /Python/Health_Management_System.py: -------------------------------------------------------------------------------- 1 | 2 | def getdate(): 3 | import datetime 4 | return datetime.datetime.now() 5 | def allclear(): 6 | f=open("harryfood.txt","w") 7 | g=open("rakeshfood.txt","w") 8 | h=open("mukeshfood.txt","w") 9 | i=open("harrywork.txt","w") 10 | j=open("rakeshwork.txt","w") 11 | k=open("mukeshwork.txt","w") 12 | f.close() 13 | g.close() 14 | h.close() 15 | i.close() 16 | j.close() 17 | k.close() 18 | def getoutput(f): 19 | for list in f: 20 | print(list) 21 | def logharryfoodf(): 22 | a=input("Enter the food: ") 23 | f=open("harryfood.txt","a") 24 | b=str(getdate()) 25 | f.write("%s %s\n"%(b,a)) 26 | f.close() 27 | def viewharryfoodf(): 28 | f=open("harryfood.txt","r") 29 | getoutput(f) 30 | f.close() 31 | def logharryworkf(): 32 | a=input("Enter the exercise: ") 33 | f=open("harrywork.txt","a") 34 | b=str(getdate()) 35 | f.write("%s %s\n"%(b,a)) 36 | f.close() 37 | def viewharryworkf(): 38 | f=open("harrywork.txt","r") 39 | getoutput(f) 40 | f.close 41 | def logmukeshworkf(): 42 | a=input("Enter the exercise: ") 43 | f=open("mukeshwork.txt","a") 44 | b=str(getdate()) 45 | f.write("%s %s\n"%(b,a)) 46 | f.close() 47 | def logmukeshfoodf(): 48 | a=input("Enter the food: ") 49 | f=open("mukeshfood.txt","a") 50 | b=str(getdate()) 51 | f.write("%s %s\n"%(b,a)) 52 | f.close() 53 | def viewmukeshworkf(): 54 | f=open("mukeshwork.txt","r") 55 | getoutput(f) 56 | f.close() 57 | def viewmukeshfoodf(): 58 | f=open("mukeshfood.txt","r") 59 | getoutput(f) 60 | f.close() 61 | def lograkeshworkf(): 62 | f=open("rakeshwork.txt","a") 63 | a=input("Enter the exercise: ") 64 | b=str(getdate()) 65 | f.write("%s %s\n"%(b,a)) 66 | f.close() 67 | def lograkeshfoodf(): 68 | f=open("rakeshfood.txt","a") 69 | a=input("Enter the food: ") 70 | b=str(getdate()) 71 | f.write("%s %s\n"%(b,a)) 72 | f.close() 73 | def viewrakeshfoodf(): 74 | f=open("rakeshfood.txt","r") 75 | getoutput(f) 76 | f.close() 77 | def viewrakeshworkf(): 78 | f=open("rakeshwork.txt","r") 79 | getoutput(f) 80 | f.close() 81 | def food(): 82 | print("press 1 to log") 83 | print("press 2 to view") 84 | a=int(input("Enter a number")) 85 | if a==1: 86 | print("1 for harry\n2 for Mukesh\n3 for rakesh") 87 | b=int(input("enter a number: ")) 88 | if b==1: 89 | logharryfoodf() 90 | elif b==2: 91 | logmukeshfoodf() 92 | elif b==3: 93 | lograkeshfoodf() 94 | else: 95 | print("enter valid number.") 96 | elif a==2: 97 | print("press 1 for Harry\n2 for Mukesh\n3 for rakesh") 98 | c=int(input("enter a number: ")) 99 | if c==1: 100 | viewharryfoodf() 101 | elif c==2: 102 | viewmukeshfoodf() 103 | elif c==3: 104 | viewrakeshfoodf() 105 | else: 106 | print("Enter valid input.") 107 | else: 108 | print("Enter a valid number!") 109 | def work(): 110 | print("press 1 to log\npress 2 to view") 111 | a=int(input("enter a number: ")) 112 | if a==1: 113 | print("press 1 for harry\npress 2 for mukesh\npress 3 for rakesh") 114 | b=int(input("Enter a number: ")) 115 | if b==1: 116 | logharryworkf() 117 | elif b==2: 118 | logmukeshworkf() 119 | elif b==3: 120 | lograkeshworkf() 121 | else: 122 | print("Enter a valid number!") 123 | elif a==2: 124 | print("press 1 for harry\n2 for mukesh\n3 for rakesh") 125 | c=int(input()) 126 | if c==1: 127 | viewharryworkf() 128 | elif c==2: 129 | viewmukeshworkf() 130 | elif c==3: 131 | viewrakeshworkf() 132 | else: 133 | print("Enter a valid number!") 134 | else: 135 | print("Enter a valid number") 136 | print("Press 'y' to run\npress 'n' to exit") 137 | r=input() 138 | while (r=="y"): 139 | 140 | print("press 1 for food\npress 2 for exercise\npress 3 for all clear") 141 | a=int(input("Enter a number: ")) 142 | 143 | if a==1: 144 | food() 145 | elif a==2: 146 | work() 147 | elif a==3: 148 | allclear() 149 | else: 150 | print("Enter valid input!!!") 151 | r=input("press 'y' to proceed\npress 'n' to exit\n ") 152 | -------------------------------------------------------------------------------- /Python/Implementation of quick sort: -------------------------------------------------------------------------------- 1 | # Function to find the partition position 2 | def partition(array, low, high): 3 | 4 | # choose the rightmost element as pivot 5 | pivot = array[high] 6 | 7 | # pointer for greater element 8 | i = low - 1 9 | 10 | # traverse through all elements 11 | # compare each element with pivot 12 | for j in range(low, high): 13 | if array[j] <= pivot: 14 | 15 | # If element smaller than pivot is found 16 | # swap it with the greater element pointed by i 17 | i = i + 1 18 | 19 | # Swapping element at i with element at j 20 | (array[i], array[j]) = (array[j], array[i]) 21 | 22 | # Swap the pivot element with the greater element specified by i 23 | (array[i + 1], array[high]) = (array[high], array[i + 1]) 24 | 25 | # Return the position from where partition is done 26 | return i + 1 27 | 28 | # function to perform quicksort 29 | 30 | 31 | def quickSort(array, low, high): 32 | if low < high: 33 | 34 | # Find pivot element such that 35 | # element smaller than pivot are on the left 36 | # element greater than pivot are on the right 37 | pi = partition(array, low, high) 38 | 39 | # Recursive call on the left of pivot 40 | quickSort(array, low, pi - 1) 41 | 42 | # Recursive call on the right of pivot 43 | quickSort(array, pi + 1, high) 44 | 45 | 46 | data = [1, 7, 4, 1, 10, 9, -2] 47 | print("Unsorted Array") 48 | print(data) 49 | 50 | size = len(data) 51 | 52 | quickSort(data, 0, size - 1) 53 | 54 | print('Sorted Array in Ascending Order:') 55 | print(data) 56 | -------------------------------------------------------------------------------- /Python/Leap_Year.py: -------------------------------------------------------------------------------- 1 | def is_leap(year): 2 | if year%4==0: 3 | if year%100!=0: 4 | pass 5 | elif year%100==0 and year%400==0: 6 | print("leap") 7 | else: 8 | print("not leap") 9 | print("leap") 10 | else: 11 | print("not leap") 12 | year = int(input("Enter the year")) 13 | is_leap(year) 14 | -------------------------------------------------------------------------------- /Python/MergeTwoBst.py: -------------------------------------------------------------------------------- 1 | # Program to merge two BSTs 2 | 3 | # Structure of a BST Node 4 | from ctypes import sizeof 5 | 6 | 7 | class Node: 8 | def __init__(self, val): 9 | self.val = val 10 | self.left = None 11 | self.right = None 12 | 13 | 14 | # Funtion to merge two BSTs 15 | def mergeTwoBST(root1, root2): 16 | res = [] 17 | s1, s2 = [], [] 18 | 19 | while root1 or root2 or s1 or s2: 20 | while root1: 21 | s1.append(root1) 22 | root1 = root1.left 23 | 24 | while root2: 25 | s2.append(root2) 26 | root2 = root2.left 27 | 28 | if not s2 or (s1 and s1[-1].val <= s2[-1].val): 29 | root1 = s1[-1] 30 | del s1[-1] 31 | res.append(root1.val) 32 | root1 = root1.right 33 | 34 | else: 35 | root2 = s2[-1] 36 | del s2[-1] 37 | res.append(root2.val) 38 | root2 = root2.right 39 | 40 | return res 41 | 42 | 43 | # Function to build a BST from the given array; 44 | def insert(root, key): 45 | if root is None: 46 | return Node(key) 47 | else: 48 | if root.val == key: 49 | return root 50 | elif root.val < key: 51 | root.right = insert(root.right, key) 52 | else: 53 | root.left = insert(root.left, key) 54 | return root 55 | 56 | 57 | def inorder(root): 58 | if root: 59 | inorder(root.left) 60 | print(root.val) 61 | inorder(root.right) 62 | 63 | 64 | # Driver program to test above functions 65 | if __name__ == '__main__': 66 | bst1 = [5, 3, 6, 2, 4] 67 | bst2 = [2, 1, 3, 7, 6] 68 | root1 = Node(bst1[0]) 69 | root2 = Node(bst2[0]) 70 | for a in range(1, len(bst1)): 71 | insert(root1, bst1[a]) 72 | for a in range(1, len(bst2)): 73 | insert(root2, bst2[a]) 74 | # inorder(root1) 75 | # inorder(root2) 76 | ans = mergeTwoBST(root1, root2) 77 | print(ans) 78 | -------------------------------------------------------------------------------- /Python/Merge_K_Sorted_List.py: -------------------------------------------------------------------------------- 1 | # There are a bunch of different solutions for this problem, let us discuss solution, using heaps here. We need to iterate over k lists and on each step to choose the minimum element among k candidates, think of it as extention of classical merge stage in merge sort. If each time we find this minimum element, using lists, overall complexity will be O(nk), where n is total number of elements in all lists. However we can do better: we create heap with the following tuples as elements: 2 | 3 | # First value of tuple is our value of nodes, because we want to sort using these values 4 | # Second value of tuple is index in lists, form where we choose this element. Why we need this? Because when we will merge this element, we need to go to the next element in the corresponding list. 5 | 6 | # Now, let us discuss main steps of algorithm: 7 | 8 | # Create dummy node in linked list, which will help us to deal with border cases, such as empty lists and so on. 9 | # curr is current element in linked list where are in now. 10 | # Put all starts of k linked lists to heap (actually there can be less than k, because some of lists can be empty) 11 | # Extract val, ind element from our heap: it will be current minumum element, and attach it to the end of constucted merged least so far, move curr iterator to the right. 12 | # If we still did not reach the end of current list, move one step to the right in this list and put new candidate to heap. 13 | # Return dummy.next. 14 | 15 | # Complexity: time complexity is O(n log k), because we have O(n) steps, where we put and remove from heap, which have at most k elements. Space complexity is O(n): because we need to return newly constructed linked list. 16 | 17 | class Solution: 18 | def mergeKLists(self, lists): 19 | dummy = curr = ListNode(0) 20 | heap = [] 21 | for ind, el in enumerate(lists): 22 | if el: heappush(heap, (el.val, ind)) 23 | 24 | while heap: 25 | val, ind = heappop(heap) 26 | curr.next = ListNode(val) 27 | curr = curr.next 28 | if lists[ind].next: 29 | lists[ind] = lists[ind].next 30 | heappush(heap, (lists[ind].val, ind)) 31 | 32 | return dummy.next 33 | 34 | 35 | -------------------------------------------------------------------------------- /Python/Minimize_the_heights_II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getMinDiff(self, arr, n, k): 3 | # code here 4 | arr.sort() 5 | ans = arr[n-1] - arr[0] 6 | smallest = arr[0] + k 7 | largest = arr[n-1] - k 8 | for i in range(n-1): 9 | mini = min(smallest, arr[i+1] - k) 10 | maxi = max(largest, arr[i] + k) 11 | if mini < 0: 12 | continue 13 | ans = min(ans, maxi-mini) 14 | return ans 15 | -------------------------------------------------------------------------------- /Python/Print the Fibonacci sequence: -------------------------------------------------------------------------------- 1 | # Program to display the Fibonacci sequence up to n-th term 2 | 3 | nterms = int(input("How many terms: ")) 4 | 5 | # first two terms 6 | n1, n2 = 0, 1 7 | count = 0 8 | 9 | # check if the number of terms is valid 10 | if nterms <= 0: 11 | print("Please enter a positive integer") 12 | # if there is only one term, return n1 13 | elif nterms == 1: 14 | print("Fibonacci sequence upto",nterms,":") 15 | print(n1) 16 | # generate fibonacci sequence 17 | else: 18 | print("Fibonacci sequence:") 19 | while count < nterms: 20 | print(n1) 21 | nth = n1 + n2 22 | # update values 23 | n1 = n2 24 | n2 = nth 25 | count += 1 26 | -------------------------------------------------------------------------------- /Python/Reversing_the_equation.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseEqn(self, s): 3 | stck=[] 4 | j='' 5 | i=0 6 | while i0: 14 | stck.append(int(j)) 15 | j='' 16 | else: 17 | stck.append(s[i]) 18 | i+=1 19 | q='' 20 | for k in stck[::-1]: 21 | q+=str(k) 22 | return q 23 | -------------------------------------------------------------------------------- /Python/Tower of Hanoi.py: -------------------------------------------------------------------------------- 1 | Tower of Hanoi 2 | 3 | // code 4 | 5 | def TowerOfHanoi(n, from_rod, to_rod, aux_rod): 6 | if n == 0: 7 | return 8 | TowerOfHanoi(n-1, from_rod, aux_rod, to_rod) 9 | print("Move disk", n, "from rod", from_rod, "to rod", to_rod) 10 | TowerOfHanoi(n-1, aux_rod, to_rod, from_rod) 11 | 12 | N = 3 13 | 14 | # A, C, B are the name of rods 15 | TowerOfHanoi(N, 'A', 'C', 'B') 16 | 17 | -------------------------------------------------------------------------------- /Python/Tower of Hanoi/Tower of Hanoi.md: -------------------------------------------------------------------------------- 1 | # Tower of Hanoi 2 | 3 | This is a very popular puzzle. There are 3 rods A, B, C. The goal is to move the stack of disks from A to C while following the rules below: 4 | 5 | - Only one disk can be moved at a time and it has to be the upper disk in the stack. 6 | - Bigger disk should not be placed on top of smaller disc. 7 | 8 | For a N disks, to move from A to C, 9 | 10 | 1. Shift N-1 disks to B using C as a temporary rod. 11 | 2. Shift the last disk to C. 12 | 3. Now use A as a temporary rod and shift all the disks from B to C. 13 | -------------------------------------------------------------------------------- /Python/Tower of Hanoi/towerofhanoi.py: -------------------------------------------------------------------------------- 1 | # Recursive logic to solve tower of hanoi problem 2 | def tower_of_hanoi(number, source, temporary, destination): 3 | if number == 1: 4 | print("Move disk 1 from", source, "to", destination) 5 | return 6 | tower_of_hanoi(n-1, source, temporary, destination) 7 | print("Move disk", n, "from", source, "to", destination) 8 | tower_of_hanoi(n-1, temporary, destination, source) 9 | 10 | # 1. Shift N-1 disks to B using C as a temporary rod. 11 | # 2. Shift the last disk to C. 12 | # 3. Now use A as a temporary rod and shift all the disks from B to C. 13 | 14 | n = int(input("Enter the number of disks")) 15 | tower_of_hanoi(n, 'A', 'B', 'C') 16 | # A is the source, C is the destination 17 | 18 | -------------------------------------------------------------------------------- /Python/Turtle.py: -------------------------------------------------------------------------------- 1 | from turtle import * 2 | import time 3 | 4 | speed(0) 5 | penup() 6 | goto(-50,0) 7 | pendown() 8 | color("#e0b936") 9 | write("Use wasd or arrow kers to move") 10 | time.sleep(1) 11 | 12 | screen=Screen() 13 | screen.bgcolor("#e0b936") 14 | 15 | penup() 16 | goto(150,1000) 17 | pendown() 18 | 19 | color("blue") 20 | begin_fill() 21 | forward(500) 22 | right(90) 23 | forward(2000) 24 | right(90) 25 | forward(500) 26 | right(90) 27 | forward(2000) 28 | end_fill() 29 | 30 | penup() 31 | goto(-200,0) 32 | shape("turtle") 33 | color("green") 34 | 35 | def goal(): 36 | if xcor()>150: 37 | color("white") 38 | write("YOU WIN!!") 39 | hideturtle() 40 | 41 | screen.onkey(None, "Up") 42 | screen.onkey(None, "Down") 43 | screen.onkey(None, "Left") 44 | screen.onkey(None, "Right") 45 | screen.onkey(None, "w") 46 | screen.onkey(None, "s") 47 | screen.onkey(None, "d") 48 | screen.onkey(None, "a") 49 | 50 | pxl=25 51 | 52 | def w(): 53 | setheading(90) 54 | forward(pxl) 55 | goal() 56 | def s(): 57 | setheading(-90) 58 | forward(pxl) 59 | goal() 60 | def a(): 61 | setheading(180) 62 | forward(pxl) 63 | goal() 64 | def d(): 65 | setheading(0) 66 | forward(pxl) 67 | goal() 68 | 69 | screen.onkey(w, "Up") 70 | screen.onkey(s, "Down") 71 | screen.onkey(a, "Left") 72 | screen.onkey(d, "Right") 73 | screen.onkey(w, "w") 74 | screen.onkey(s, "s") 75 | screen.onkey(d, "d") 76 | screen.onkey(a, "a") 77 | 78 | screen.listen() 79 | 80 | done() 81 | -------------------------------------------------------------------------------- /Python/acronym.py: -------------------------------------------------------------------------------- 1 | user_input = str(input("Enter a Phrase: ")) 2 | text = user_input.split() 3 | a = " " 4 | for i in text: 5 | a = a+str(i[0]).upper() 6 | print(a) -------------------------------------------------------------------------------- /Python/analogClock.py: -------------------------------------------------------------------------------- 1 | try: 2 | import Tkinter 3 | except: 4 | import tkinter as Tkinter 5 | 6 | import math # Required For Coordinates Calculation 7 | import time # Required For Time Handling 8 | # 9 | # 10 | # class 11 | class main(Tkinter.Tk): 12 | def __init__(self): 13 | Tkinter.Tk.__init__(self) 14 | self.x=150 # Center Point x 15 | self.y=150 # Center Point 16 | self.length=50 # Stick Length 17 | self.creating_all_function_trigger() 18 | 19 | # Creating Trigger For Other Functions 20 | def creating_all_function_trigger(self): 21 | self.create_canvas_for_shapes() 22 | self.creating_background_() 23 | self.creating_sticks() 24 | return 25 | 26 | # Creating Background 27 | def creating_background_(self): 28 | self.image=Tkinter.PhotoImage(file='clock.gif') 29 | self.canvas.create_image(150,150, image=self.image) 30 | return 31 | 32 | # creating Canvas 33 | def create_canvas_for_shapes(self): 34 | self.canvas=Tkinter.Canvas(self, bg='black') 35 | self.canvas.pack(expand='yes',fill='both') 36 | return 37 | 38 | # Creating Moving Sticks 39 | def creating_sticks(self): 40 | self.sticks=[] 41 | for i in range(3): 42 | store=self.canvas.create_line(self.x, self.y,self.x+self.length,self.y+self.length,width=2, fill='red') 43 | self.sticks.append(store) 44 | return 45 | 46 | # Function Need Regular Update 47 | def update_class(self): 48 | now=time.localtime() 49 | t = time.strptime(str(now.tm_hour), "%H") 50 | hour = int(time.strftime( "%I", t ))*5 51 | now=(hour,now.tm_min,now.tm_sec) 52 | # Changing Stick Coordinates 53 | for n,i in enumerate(now): 54 | x,y=self.canvas.coords(self.sticks[n])[0:2] 55 | cr=[x,y] 56 | cr.append(self.length*math.cos(math.radians(i*6)-math.radians(90))+self.x) 57 | cr.append(self.length*math.sin(math.radians(i*6)-math.radians(90))+self.y) 58 | self.canvas.coords(self.sticks[n], tuple(cr)) 59 | return 60 | 61 | # Main Function Trigger 62 | if __name__ == '__main__': 63 | root=main() 64 | 65 | # Creating Main Loop 66 | while True: 67 | root.update() 68 | root.update_idletasks() 69 | root.update_class() 70 | -------------------------------------------------------------------------------- /Python/captain-shield.py: -------------------------------------------------------------------------------- 1 | import turtle as tt 2 | 3 | def circle (radius , color) : 4 | tt.color (color) 5 | tt.begin_fill() 6 | tt.circle(radius) 7 | tt.end_fill() 8 | 9 | tt.goto(-30,-280) 10 | circle(300,'dark red') 11 | 12 | tt.goto(-30,-240) 13 | circle(260,'white') 14 | 15 | tt.goto(-30,-200) 16 | circle(220,'dark red') 17 | 18 | tt.goto(-30,-160) 19 | circle(180,'royal blue') 20 | 21 | tt.goto(-200,75) 22 | tt.begin_fill() 23 | tt.color('white') 24 | 25 | for i in range(5): 26 | tt.forward(340) 27 | tt.right(144) 28 | tt.end_fill() 29 | tt.hideturtle() 30 | -------------------------------------------------------------------------------- /Python/character_rangoli.py: -------------------------------------------------------------------------------- 1 | import string 2 | alpha = string.ascii_lowercase 3 | 4 | n = int(input()) 5 | L = [] 6 | for i in range(n): 7 | s = "-".join(alpha[i:n]) 8 | L.append((s[::-1]+s[1:]).center(4*n-3, "-")) 9 | print('\n'.join(L[:0:-1]+L)) 10 | -------------------------------------------------------------------------------- /Python/countdowntimer.py: -------------------------------------------------------------------------------- 1 | import time 2 | from tkinter import * 3 | from tkinter import messagebox 4 | 5 | 6 | # creating Tk window 7 | root = Tk() 8 | 9 | # setting geometry of tk window 10 | root.geometry("300x250") 11 | 12 | # Using title() to display a message in 13 | # the dialogue box of the message in the 14 | # title bar. 15 | root.title("Time Counter") 16 | 17 | # Declaration of variables 18 | hour=StringVar() 19 | minute=StringVar() 20 | second=StringVar() 21 | 22 | # setting the default value as 0 23 | hour.set("00") 24 | minute.set("00") 25 | second.set("00") 26 | 27 | # Use of Entry class to take input from the user 28 | hourEntry= Entry(root, width=3, font=("Arial",18,""), 29 | textvariable=hour) 30 | hourEntry.place(x=80,y=20) 31 | 32 | minuteEntry= Entry(root, width=3, font=("Arial",18,""), 33 | textvariable=minute) 34 | minuteEntry.place(x=130,y=20) 35 | 36 | secondEntry= Entry(root, width=3, font=("Arial",18,""), 37 | textvariable=second) 38 | secondEntry.place(x=180,y=20) 39 | 40 | 41 | def submit(): 42 | try: 43 | # the input provided by the user is 44 | # stored in here :temp 45 | temp = int(hour.get())*3600 + int(minute.get())*60 + int(second.get()) 46 | except: 47 | print("Please input the right value") 48 | while temp >-1: 49 | 50 | # divmod(firstvalue = temp//60, secondvalue = temp%60) 51 | mins,secs = divmod(temp,60) 52 | 53 | # Converting the input entered in mins or secs to hours, 54 | # mins ,secs(input = 110 min --> 120*60 = 6600 => 1hr : 55 | # 50min: 0sec) 56 | hours=0 57 | if mins >60: 58 | 59 | # divmod(firstvalue = temp//60, secondvalue 60 | # = temp%60) 61 | hours, mins = divmod(mins, 60) 62 | 63 | # using format () method to store the value up to 64 | # two decimal places 65 | hour.set("{0:2d}".format(hours)) 66 | minute.set("{0:2d}".format(mins)) 67 | second.set("{0:2d}".format(secs)) 68 | 69 | # updating the GUI window after decrementing the 70 | # temp value every time 71 | root.update() 72 | time.sleep(1) 73 | 74 | # when temp value = 0; then a messagebox pop's up 75 | # with a message:"Time's up" 76 | if (temp == 0): 77 | messagebox.showinfo("Time Countdown", "Time's up ") 78 | 79 | # after every one sec the value of temp will be decremented 80 | # by one 81 | temp -= 1 82 | 83 | # button widget 84 | btn = Button(root, text='Set Time Countdown', bd='5', 85 | command= submit) 86 | btn.place(x = 70,y = 120) 87 | 88 | # infinite loop which is required to 89 | # run tkinter program infinitely 90 | # until an interrupt occurs 91 | root.mainloop() 92 | -------------------------------------------------------------------------------- /Python/digitalclock.py: -------------------------------------------------------------------------------- 1 | # importing whole module 2 | from tkinter import * 3 | from tkinter.ttk import * 4 | 5 | # importing strftime function to system time 6 | 7 | from time import strftime 8 | 9 | # creating tkinter window 10 | root = Tk() 11 | root.title('Clock') 12 | 13 | # This function is used to display time on the label 14 | def time(): 15 | string = strftime("%H : %M : %S") 16 | lbl.config(text = string) 17 | lbl.after(100, time) 18 | 19 | # Styling the label widget so that clock will look more attractive 20 | lbl = Label(root, font = ('calibri', 40, 'bold')) 21 | 22 | # Placing clock at the centre of the tkinter window 23 | lbl.pack(anchor = 'center') 24 | time() 25 | mainloop() -------------------------------------------------------------------------------- /Python/eggCatcher.py: -------------------------------------------------------------------------------- 1 | from itertools import cycle 2 | from random import randrange 3 | from tkinter import Canvas, Tk, messagebox, font 4 | 5 | canvas_width = 800 6 | canvas_height = 400 7 | 8 | root = Tk() 9 | root.title("Egg Catcher") 10 | c = Canvas(root, width=canvas_width, height=canvas_height, background="deep sky blue") 11 | c.create_rectangle(-5, canvas_height-100, canvas_width+5, canvas_height+5, fill="sea green", width=0) 12 | c.create_oval(-80, -80, 120, 120, fill='orange', width=0) 13 | c.pack() 14 | 15 | color_cycle = cycle(["light blue", "light green", "light pink", "light yellow", "light cyan"]) 16 | egg_width = 45 17 | egg_height = 55 18 | egg_score = 10 19 | egg_speed = 500 20 | egg_interval = 4000 21 | difficulty = 0.95 22 | catcher_color = "blue" 23 | catcher_width = 100 24 | catcher_height = 100 25 | catcher_startx = canvas_width / 2 - catcher_width / 2 26 | catcher_starty = canvas_height - catcher_height - 20 27 | catcher_startx2 = catcher_startx + catcher_width 28 | catcher_starty2 = catcher_starty + catcher_height 29 | 30 | catcher = c.create_arc(catcher_startx, catcher_starty, catcher_startx2, catcher_starty2, start=200, extent=140, style="arc", outline=catcher_color, width=3) 31 | game_font = font.nametofont("TkFixedFont") 32 | game_font.config(size=18) 33 | 34 | 35 | score = 0 36 | score_text = c.create_text(10, 10, anchor="nw", font=game_font, fill="darkblue", text="Score: "+ str(score)) 37 | 38 | lives_remaining = 3 39 | lives_text = c.create_text(canvas_width-10, 10, anchor="ne", font=game_font, fill="darkblue", text="Lives: "+ str(lives_remaining)) 40 | 41 | eggs = [] 42 | 43 | def create_egg(): 44 | x = randrange(10, 740) 45 | y = 40 46 | new_egg = c.create_oval(x, y, x+egg_width, y+egg_height, fill=next(color_cycle), width=0) 47 | eggs.append(new_egg) 48 | root.after(egg_interval, create_egg) 49 | 50 | def move_eggs(): 51 | for egg in eggs: 52 | (eggx, eggy, eggx2, eggy2) = c.coords(egg) 53 | c.move(egg, 0, 10) 54 | if eggy2 > canvas_height: 55 | egg_dropped(egg) 56 | root.after(egg_speed, move_eggs) 57 | 58 | def egg_dropped(egg): 59 | eggs.remove(egg) 60 | c.delete(egg) 61 | lose_a_life() 62 | if lives_remaining == 0: 63 | messagebox.showinfo("Game Over!", "Final Score: "+ str(score)) 64 | root.destroy() 65 | 66 | def lose_a_life(): 67 | global lives_remaining 68 | lives_remaining -= 1 69 | c.itemconfigure(lives_text, text="Lives: "+ str(lives_remaining)) 70 | 71 | def check_catch(): 72 | (catcherx, catchery, catcherx2, catchery2) = c.coords(catcher) 73 | for egg in eggs: 74 | (eggx, eggy, eggx2, eggy2) = c.coords(egg) 75 | if catcherx < eggx and eggx2 < catcherx2 and catchery2 - eggy2 < 40: 76 | eggs.remove(egg) 77 | c.delete(egg) 78 | increase_score(egg_score) 79 | root.after(100, check_catch) 80 | 81 | def increase_score(points): 82 | global score, egg_speed, egg_interval 83 | score += points 84 | egg_speed = int(egg_speed * difficulty) 85 | egg_interval = int(egg_interval * difficulty) 86 | c.itemconfigure(score_text, text="Score: "+ str(score)) 87 | 88 | def move_left(event): 89 | (x1, y1, x2, y2) = c.coords(catcher) 90 | if x1 > 0: 91 | c.move(catcher, -20, 0) 92 | 93 | def move_right(event): 94 | (x1, y1, x2, y2) = c.coords(catcher) 95 | if x2 < canvas_width: 96 | c.move(catcher, 20, 0) 97 | 98 | c.bind("", move_left) 99 | c.bind("", move_right) 100 | c.focus_set() 101 | root.after(1000, create_egg) 102 | root.after(1000, move_eggs) 103 | root.after(1000, check_catch) 104 | root.mainloop() 105 | -------------------------------------------------------------------------------- /Python/insertion_sort.py: -------------------------------------------------------------------------------- 1 | def insertion_sort(collection: list) -> list: 2 | for insert_index, insert_value in enumerate(collection[1:]): 3 | temp_index = insert_index 4 | while insert_index >= 0 and insert_value < collection[insert_index]: 5 | collection[insert_index + 1] = collection[insert_index] 6 | insert_index -= 1 7 | if insert_index != temp_index: 8 | collection[insert_index + 1] = insert_value 9 | return collection 10 | 11 | 12 | if __name__ == "__main__": 13 | from doctest import testmod 14 | 15 | testmod() 16 | 17 | user_input = input("Enter numbers separated by a comma:\n").strip() 18 | unsorted = [int(item) for item in user_input.split(",")] 19 | print(f"{insertion_sort(unsorted) = }") -------------------------------------------------------------------------------- /Python/number_guessing.py: -------------------------------------------------------------------------------- 1 | import random 2 | import math 3 | # Taking Inputs 4 | lower = int(input("Enter Lower bound:- ")) 5 | 6 | # Taking Inputs 7 | upper = int(input("Enter Upper bound:- ")) 8 | 9 | # generating random number between 10 | # the lower and upper 11 | x = random.randint(lower, upper) 12 | print("\n\tYou've only ", 13 | round(math.log(upper - lower + 1, 2)), 14 | " chances to guess the integer!\n") 15 | 16 | # Initializing the number of guesses. 17 | count = 0 18 | 19 | # for calculation of minimum number of 20 | # guesses depends upon range 21 | while count < math.log(upper - lower + 1, 2): 22 | count += 1 23 | 24 | # taking guessing number as input 25 | guess = int(input("Guess a number:- ")) 26 | 27 | # Condition testing 28 | if x == guess: 29 | print("Congratulations you did it in ", 30 | count, " try") 31 | # Once guessed, loop will break 32 | break 33 | elif x > guess: 34 | print("You guessed too small!") 35 | elif x < guess: 36 | print("You Guessed too high!") 37 | 38 | # If Guessing is more than required guesses, 39 | # shows this output. 40 | if count >= math.log(upper - lower + 1, 2): 41 | print("\nThe number is %d" % x) 42 | print("\tBetter Luck Next time!") 43 | 44 | # Better to use This source Code on pycharm! 45 | -------------------------------------------------------------------------------- /Python/pPrinting_matrix_in_spiral.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def spiralOrder(matrix): 5 | ans = [] 6 | 7 | if (len(matrix) == 0): 8 | return ans 9 | 10 | m = len(matrix) 11 | n = len(matrix[0]) 12 | seen = [[0 for i in range(n)] for j in range(m)] 13 | dr = [0, 1, 0, -1] 14 | dc = [1, 0, -1, 0] 15 | x = 0 16 | y = 0 17 | di = 0 18 | 19 | # Iterate from 0 to R * C - 1 20 | for i in range(m * n): 21 | ans.append(matrix[x][y]) 22 | seen[x][y] = True 23 | cr = x + dr[di] 24 | cc = y + dc[di] 25 | 26 | if (0 <= cr and cr < m and 0 <= cc and cc < n and not(seen[cr][cc])): 27 | x = cr 28 | y = cc 29 | else: 30 | di = (di + 1) % 4 31 | x += dr[di] 32 | y += dc[di] 33 | return ans 34 | 35 | 36 | if __name__ == "__main__": 37 | a = [[1, 2, 3, 4], 38 | [5, 6, 7, 8], 39 | [9, 10, 11, 12], 40 | [13, 14, 15, 16]] 41 | 42 | # Function call 43 | for x in spiralOrder(a): 44 | print(x, end=" ") 45 | print() 46 | -------------------------------------------------------------------------------- /Python/pet.py: -------------------------------------------------------------------------------- 1 | from tkinter import HIDDEN, NORMAL, Tk, Canvas 2 | def toggle_eyes(): 3 | current_color = c.itemcget(eye_left, 'fill') 4 | new_color = c.body_color if current_color == 'white' else 'white' 5 | current_state = c.itemcget(pupil_left, 'state') 6 | new_state = NORMAL if current_state == HIDDEN else HIDDEN 7 | c.itemconfigure(pupil_left, state=new_state) 8 | c.itemconfigure(pupil_right, state=new_state) 9 | c.itemconfigure(eye_left, fill=new_color) 10 | c.itemconfigure(eye_right, fill=new_color) 11 | 12 | def blink(): 13 | toggle_eyes() 14 | root.after(250, toggle_eyes) 15 | root.after(3000, blink) 16 | 17 | def toggle_pupils(): 18 | if not c.eyes_crossed: 19 | c.move(pupil_left, 10, -5) 20 | c.move(pupil_right, -10, -5) 21 | c.eyes_crossed = True 22 | else: 23 | c.move(pupil_left, -10, 5) 24 | c.move(pupil_right, 10, 5) 25 | c.eyes_crossed = False 26 | 27 | def toggle_tongue(): 28 | if not c.tongue_out: 29 | c.itemconfigure(tongue_tip, state=NORMAL) 30 | c.itemconfigure(tongue_main, state=NORMAL) 31 | c.tongue_out = True 32 | else: 33 | c.itemconfigure(tongue_tip, state=HIDDEN) 34 | c.itemconfigure(tongue_main, state=HIDDEN) 35 | c.tongue_out = False 36 | def cheeky(event): 37 | toggle_tongue() 38 | toggle_pupils() 39 | hide_happy(event) 40 | root.after(1000, toggle_tongue) 41 | root.after(1000, toggle_pupils) 42 | return 43 | 44 | def show_happy(event): 45 | if (20 <= event.x and event.x <= 350) and (20 <= event.y and event.y <= 350): 46 | c.itemconfigure(cheek_left, state=NORMAL) 47 | c.itemconfigure(cheek_right, state=NORMAL) 48 | c.itemconfigure(mouth_happy, state=NORMAL) 49 | c.itemconfigure(mouth_normal, state=HIDDEN) 50 | c.itemconfigure(mouth_sad, state=HIDDEN) 51 | c.happy_level = 10 52 | return 53 | 54 | def hide_happy(event): 55 | c.itemconfigure(cheek_left, state=HIDDEN) 56 | c.itemconfigure(cheek_right, state=HIDDEN) 57 | c.itemconfigure(mouth_happy, state=HIDDEN) 58 | c.itemconfigure(mouth_normal, state=NORMAL) 59 | c.itemconfigure(mouth_sad, state=HIDDEN) 60 | return 61 | 62 | def sad(): 63 | if c.happy_level == 0: 64 | c.itemconfigure(mouth_happy, state=HIDDEN) 65 | c.itemconfigure(mouth_normal, state=HIDDEN) 66 | c.itemconfigure(mouth_sad, state=NORMAL) 67 | else: 68 | c.happy_level -= 1 69 | root.after(5000, sad) 70 | 71 | root = Tk() 72 | c = Canvas(root, width=400, height=400) 73 | c.configure(bg='dark blue', highlightthickness=0) 74 | c.body_color = 'SkyBlue1' 75 | 76 | body = c.create_oval(35, 20, 365, 350, outline=c.body_color, fill=c.body_color) 77 | ear_left = c.create_polygon(75, 80, 75, 10, 165, 70, outline=c.body_color, fill=c.body_color) 78 | ear_right = c.create_polygon(255, 45, 325, 10, 320, 70, outline=c.body_color, fill=c.body_color) 79 | foot_left = c.create_oval(65, 320, 145, 360, outline=c.body_color, fill=c.body_color) 80 | foot_right = c.create_oval(250, 320, 330, 360, outline=c.body_color, fill=c.body_color) 81 | 82 | eye_left = c.create_oval(130, 110, 160, 170, outline='black', fill='white') 83 | pupil_left = c.create_oval(140, 145, 150, 155, outline='black', fill='black') 84 | eye_right = c.create_oval(230, 110, 260, 170, outline='black', fill='white') 85 | pupil_right = c.create_oval(240, 145, 250, 155, outline='black', fill='black') 86 | 87 | 88 | mouth_normal = c.create_line(170, 250, 200, 272, 230, 250, smooth=1, width=2, state=NORMAL) 89 | mouth_happy = c.create_line(170, 250, 200, 282, 230, 250, smooth=1, width=2, state=HIDDEN) 90 | mouth_sad = c.create_line(170, 250, 200, 232, 230, 250, smooth=1, width=2, state=HIDDEN) 91 | tongue_main = c.create_rectangle(170, 250, 230, 290, outline='red', fill='red', state=HIDDEN) 92 | tongue_tip = c.create_oval(170, 285, 230, 300, outline='red', fill='red', state=HIDDEN) 93 | 94 | cheek_left = c.create_oval(70, 180, 120, 230, outline='pink', fill='pink', state=HIDDEN) 95 | cheek_right = c.create_oval(280, 180, 330, 230, outline='pink', fill='pink', state=HIDDEN) 96 | 97 | c.pack() 98 | c.bind('', show_happy) 99 | c.bind('', hide_happy) 100 | c.bind('', cheeky) 101 | 102 | c.happy_level = 10 103 | c.eyes_crossed = False 104 | c.tongue_out = False 105 | 106 | root.after(1000, blink) 107 | root.after(5000, sad) 108 | root.mainloop() -------------------------------------------------------------------------------- /Python/pokemon.py: -------------------------------------------------------------------------------- 1 | # python code to train pokemon 2 | powers = [3, 8, 9, 7] 3 | 4 | mini, maxi = 0, 0 5 | 6 | for power in powers: 7 | if mini == 0 and maxi == 0: 8 | mini, maxi = powers[0], powers[0] 9 | print(mini, maxi) 10 | else: 11 | mini = min(mini, power) 12 | maxi = max(maxi, power) 13 | print(mini, maxi) 14 | 15 | # Time Complexity is O(N) with Space Complexity O(1) 16 | -------------------------------------------------------------------------------- /Python/price_email.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | import smtplib 4 | 5 | URL = "" # add the link 6 | headers = { 7 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/87.0.4280.141 Safari/537.36 OPR/73.0.3856.396"} # add custom headers 8 | 9 | def send_email(): 10 | sever=smtplib.SMTP('smtp.gmail.com',587) 11 | sever.ehlo() 12 | sever.starttls() 13 | sever.ehlo() 14 | 15 | sever.login('','') # Add credentials in the format is {user},{password} 16 | body=URL 17 | msg=f"Body:{body}\nThe price has dropped" 18 | sever.sendmail("","",msg) 19 | sever.quit() 20 | 21 | def check_price(): 22 | 23 | page = requests.get(URL, headers=headers) 24 | soup = BeautifulSoup(page.content, 'html.parser') 25 | price = soup.find(id='priceblock_ourprice').getText() 26 | price=price.replace(",","") 27 | price=price.split('.',1) 28 | sub_price=price[0] 29 | sub_price=int(sub_price) 30 | print(sub_price) 31 | if sub_price < 2999: 32 | send_email() 33 | 34 | check_price() 35 | -------------------------------------------------------------------------------- /Python/quizGame.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | 4 | class Question: 5 | def __init__(self,text,ans): 6 | self.text = text 7 | self.answer = ans 8 | 9 | class QuestionBrain: 10 | def __init__(self,l): 11 | self.n=0 12 | self.qlist = l 13 | self.score = 0 14 | 15 | def nextQuestion(self): 16 | que = self.qlist[self.n] 17 | self.n+=1 18 | a = input(f"Q.{self.n}: {que.text} (True/False) ? :") 19 | self.check(a,que.answer) 20 | 21 | def still_have_question(self): 22 | return self.n < len(self.qlist) 23 | 24 | def check(self,ans,crt): 25 | if ans.lower()==crt.lower(): 26 | self.score +=1 27 | print("You are Right") 28 | else: 29 | print("You are Wrong") 30 | print(f"Your score : {self.score}/{self.n}") 31 | 32 | def finish(self): 33 | print(f"You have completed the quiz..\nYour final score : {self.score}/{self.n}") 34 | 35 | class Data: 36 | def __init__(self): 37 | self.question_data=[] 38 | self.amount=10 39 | self.category=9 40 | self.difficulty='easy' 41 | self.category_name = [ 42 | {'name':"General Knowledge","id":"9"}, 43 | {'name':"Books","id":"10"}, 44 | {'name':"Films","id":"11"}, 45 | {'name':"Musics","id":"12"}, 46 | {'name':"Musical & Theatre","id":"13"}, 47 | {'name':"Television","id":"14"}, 48 | {'name':"Video Games","id":"15"}, 49 | {'name':"Board Games","id":"16"}, 50 | {'name':"Science & Nature","id":"16"}, 51 | {'name':"Computer","id":"18"}, 52 | {'name':"Maths","id":"19"}, 53 | {'name':"Mythology","id":"20"}, 54 | {'name':"Sports","id":"21"}, 55 | {'name':"Geology","id":"22"}, 56 | {'name':"History","id":"23"}, 57 | {'name':"Politics","id":"24"}, 58 | {'name':"Art","id":"25"}, 59 | {'name':"Celebrity","id":"26"}, 60 | {'name':"Animal","id":"27"}, 61 | {'name':"Vehical","id":"28"}, 62 | {'name':"Comics","id":"29"}, 63 | {'name':"Gadgets","id":"30"} 64 | ] 65 | 66 | def showCategory(self): 67 | for i in self.category_name: 68 | print(f"{i['name']}--{int(i['id'])-9}",end=" ") 69 | print() 70 | 71 | def create(self): 72 | self.amount = int(input("Number of Questions (less than 50):"))%51 73 | self.showCategory() 74 | self.category = ((int(input("Choose a Category:"))%22) + 9) 75 | t= True 76 | while t: 77 | self.difficulty = input("Choose a difficulty level (easy/medium/hard): ").lower() 78 | if self.difficulty =="easy" or self.difficulty =="medium" or self.difficulty == "hard": 79 | break 80 | else: print("Choose a correct_difficulty level..") 81 | self.create_data() 82 | 83 | def printdata(self): 84 | print(self.difficulty, self.amount, self.category) 85 | 86 | def create_data(self): 87 | # self.printdata() 88 | url = f'https://opentdb.com/api.php?amount={self.amount}&category={self.category}&difficulty={self.difficulty}&type=boolean' 89 | # print(url) 90 | res =requests.get(url).json() 91 | for i in res['results']: 92 | d = {"text":i['question'],"answer":i['correct_answer']} 93 | self.question_data.append(d) 94 | 95 | if len(self.question_data)==0: 96 | url = f'https://opentdb.com/api.php?amount={self.amount}&type=boolean' 97 | res =requests.get(url).json() 98 | for i in res['results']: 99 | d = {"text":i['question'],"answer":i['correct_answer']} 100 | self.question_data.append(d) 101 | print(f"\n\nUnable to find as per your request, {res['results'][0]['category']} is the category we choose for you") 102 | else:print("\n\n") 103 | 104 | 105 | qbank = [] 106 | 107 | data = Data() 108 | data.create() 109 | 110 | for i in data.question_data: 111 | # print(i) 112 | q = Question(i['text'], i['answer'],) 113 | qbank.append(q) 114 | 115 | quiz = QuestionBrain(qbank) 116 | 117 | print('\n\n\n') 118 | while quiz.still_have_question(): 119 | quiz.nextQuestion() 120 | 121 | quiz.finish() 122 | -------------------------------------------------------------------------------- /Python/rangoli.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | 3 | ab = 'abcdefghijklmnopqrstuvwxyz' 4 | 5 | def rangoli_line(n,N): 6 | """ N is rangoli size, n is the number of letters in this line 7 | """ 8 | center_letter = ab[N-n] 9 | sides = [] 10 | 11 | side_length = n-1 12 | for i in range(side_length): 13 | sides.append(ab[(N-n)+i+1]) 14 | 15 | right_side = '-'.join(sides) 16 | left_side = ''.join(reversed(right_side)) 17 | 18 | line = left_side + '-' + center_letter + '-' + right_side 19 | 20 | return(line) 21 | 22 | def rangoli_lines(N): 23 | if N == 1: 24 | print('a') 25 | return 26 | 27 | s = [] 28 | for n in range(1,N+1): 29 | s.append(rangoli_line(n,N)) 30 | 31 | padding_length = (N - 1)*4 + 1 32 | for l in s: 33 | print('{:-^{}}'.format(l, padding_length)) 34 | for l in reversed(s[:-1]): 35 | print('{:-^{}}'.format(l, padding_length)) 36 | 37 | rangoli_lines(N) -------------------------------------------------------------------------------- /Python/roadCrossing Game.py: -------------------------------------------------------------------------------- 1 | import time 2 | from turtle import Screen,Turtle 3 | from random import randint,choice 4 | 5 | FONT = ("Courier", 24, "normal") 6 | 7 | class Scoreboard(Turtle): 8 | def __init__(self): 9 | super().__init__() 10 | self.score = 0 11 | self.color("black") 12 | self.penup() 13 | self.hideturtle() 14 | self.refresh() 15 | 16 | def refresh(self): 17 | self.goto(-280,260) 18 | self.write(arg=f"score:{self.score} ",font=FONT) 19 | 20 | def game_over(self): 21 | self.goto(0,0) 22 | self.write(arg=f"Game Over",align="center",font=FONT) 23 | 24 | def addScore(self): 25 | self.score += 1 26 | self.clear() 27 | self.refresh() 28 | 29 | STARTING_POSITION = (0, -280) 30 | MOVE_DISTANCE = 10 31 | FINISH_LINE_Y = 280 32 | 33 | class Player(Turtle): 34 | def __init__(self): 35 | super().__init__() 36 | self.shape("turtle") 37 | self.penup() 38 | self.right(-90) 39 | self.restart() 40 | 41 | def move(self): 42 | self.forward(MOVE_DISTANCE) 43 | 44 | def restart(self): 45 | self.goto(STARTING_POSITION) 46 | 47 | COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] 48 | STARTING_MOVE_DISTANCE = 5 49 | MOVE_INCREMENT = 10 50 | 51 | class CarManager: 52 | def __init__(self): 53 | super().__init__() 54 | self.cars = [] 55 | self.distance = STARTING_MOVE_DISTANCE 56 | self.create() 57 | 58 | def create(self): 59 | c = Turtle("square") 60 | c.shapesize(1,2) 61 | c.penup() 62 | c.color(choice(COLORS)) 63 | c.setheading(180) 64 | c.goto(300,randint(-250,250)) 65 | self.cars.append(c) 66 | 67 | 68 | def move(self): 69 | for c in self.cars: 70 | c.forward(self.distance) 71 | 72 | def nextLevel(self): 73 | self.distance += MOVE_INCREMENT 74 | 75 | screen = Screen() 76 | screen.setup(width=600, height=600) 77 | screen.tracer(0) 78 | 79 | p = Player() 80 | c = CarManager() 81 | sc = Scoreboard() 82 | 83 | screen.listen() 84 | screen.onkey(p.move,"Up") 85 | 86 | game_is_on = True 87 | time_counter = 0 88 | while game_is_on: 89 | if time_counter % 6 == 5: 90 | c.create() 91 | time.sleep(0.1) 92 | screen.update() 93 | c.move() 94 | time_counter += 1 95 | 96 | for car in c.cars: 97 | if car.distance(p) < 20: 98 | game_is_on = False 99 | sc.game_over() 100 | 101 | if p.ycor() >= FINISH_LINE_Y: 102 | c.nextLevel() 103 | p.restart() 104 | sc.addScore() 105 | 106 | screen.exitonclick() 107 | -------------------------------------------------------------------------------- /Python/rockpaperscissorgame.py: -------------------------------------------------------------------------------- 1 | # import random module 2 | import random 3 | 4 | # Print multiline instruction 5 | # performstring concatenation of string 6 | print("Winning Rules of the Rock paper scissor game as follows: \n" 7 | +"Rock vs paper->paper wins \n" 8 | + "Rock vs scissor->Rock wins \n" 9 | +"paper vs scissor->scissor wins \n") 10 | 11 | while True: 12 | print("Enter choice \n 1 for Rock, \n 2 for paper, and \n 3 for scissor \n") 13 | 14 | # take the input from user 15 | choice = int(input("User turn: ")) 16 | 17 | # OR is the short-circuit operator 18 | # if any one of the condition is true 19 | # then it return True value 20 | 21 | # looping until user enter invalid input 22 | while choice > 3 or choice < 1: 23 | choice = int(input("enter valid input: ")) 24 | 25 | 26 | # initialize value of choice_name variable 27 | # corresponding to the choice value 28 | if choice == 1: 29 | choice_name = 'Rock' 30 | elif choice == 2: 31 | choice_name = 'paper' 32 | else: 33 | choice_name = 'scissor' 34 | 35 | # print user choice 36 | print("user choice is: " + choice_name) 37 | print("\nNow its computer turn.......") 38 | 39 | # Computer chooses randomly any number 40 | # among 1 , 2 and 3. Using randint method 41 | # of random module 42 | comp_choice = random.randint(1, 3) 43 | 44 | # looping until comp_choice value 45 | # is equal to the choice value 46 | while comp_choice == choice: 47 | comp_choice = random.randint(1, 3) 48 | 49 | # initialize value of comp_choice_name 50 | # variable corresponding to the choice value 51 | if comp_choice == 1: 52 | comp_choice_name = 'Rock' 53 | elif comp_choice == 2: 54 | comp_choice_name = 'paper' 55 | else: 56 | comp_choice_name = 'scissor' 57 | 58 | print("Computer choice is: " + comp_choice_name) 59 | 60 | print(choice_name + " V/s " + comp_choice_name) 61 | #we need to check of a draw 62 | if choice == comp_choice: 63 | print("Draw=> ", end = "") 64 | result = Draw 65 | 66 | # condition for winning 67 | if((choice == 1 and comp_choice == 2) or 68 | (choice == 2 and comp_choice ==1 )): 69 | print("paper wins => ", end = "") 70 | result = "paper" 71 | 72 | elif((choice == 1 and comp_choice == 3) or 73 | (choice == 3 and comp_choice == 1)): 74 | print("Rock wins =>", end = "") 75 | result = "Rock" 76 | else: 77 | print("scissor wins =>", end = "") 78 | result = "scissor" 79 | 80 | # Printing either user or computer wins or draw 81 | if result == Draw: 82 | print("<== Its a tie ==>") 83 | if result == choice_name: 84 | print("<== User wins ==>") 85 | else: 86 | print("<== Computer wins ==>") 87 | 88 | print("Do you want to play again? (Y/N)") 89 | ans = input().lower 90 | 91 | 92 | # if user input n or N then condition is True 93 | if ans == 'n': 94 | break 95 | 96 | # after coming out of the while loop 97 | # we print thanks for playing 98 | print("\nThanks for playing") 99 | -------------------------------------------------------------------------------- /Python/snek.py: -------------------------------------------------------------------------------- 1 | # import required modules 2 | import turtle 3 | import time 4 | import random 5 | 6 | delay = 0.1 7 | score = 0 8 | high_score = 0 9 | 10 | 11 | 12 | # Creating a window screen 13 | wn = turtle.Screen() 14 | wn.title("Snake Game") 15 | wn.bgcolor("blue") 16 | # the width and height can be put as user's choice 17 | wn.setup(width=600, height=600) 18 | wn.tracer(0) 19 | 20 | # head of the snake 21 | head = turtle.Turtle() 22 | head.shape("square") 23 | head.color("white") 24 | head.penup() 25 | head.goto(0, 0) 26 | head.direction = "Stop" 27 | 28 | # food in the game 29 | food = turtle.Turtle() 30 | colors = random.choice(['red', 'green', 'black']) 31 | shapes = random.choice(['square', 'triangle', 'circle']) 32 | food.speed(0) 33 | food.shape(shapes) 34 | food.color(colors) 35 | food.penup() 36 | food.goto(0, 100) 37 | 38 | pen = turtle.Turtle() 39 | pen.speed(0) 40 | pen.shape("square") 41 | pen.color("white") 42 | pen.penup() 43 | pen.hideturtle() 44 | pen.goto(0, 250) 45 | pen.write("Score : 0 High Score : 0", align="center", 46 | font=("candara", 24, "bold")) 47 | 48 | 49 | 50 | # assigning key directions 51 | def group(): 52 | if head.direction != "down": 53 | head.direction = "up" 54 | 55 | 56 | def godown(): 57 | if head.direction != "up": 58 | head.direction = "down" 59 | 60 | 61 | def goleft(): 62 | if head.direction != "right": 63 | head.direction = "left" 64 | 65 | 66 | def goright(): 67 | if head.direction != "left": 68 | head.direction = "right" 69 | 70 | 71 | def move(): 72 | if head.direction == "up": 73 | y = head.ycor() 74 | head.sety(y+20) 75 | if head.direction == "down": 76 | y = head.ycor() 77 | head.sety(y-20) 78 | if head.direction == "left": 79 | x = head.xcor() 80 | head.setx(x-20) 81 | if head.direction == "right": 82 | x = head.xcor() 83 | head.setx(x+20) 84 | 85 | 86 | 87 | wn.listen() 88 | wn.onkeypress(group, "w") 89 | wn.onkeypress(godown, "s") 90 | wn.onkeypress(goleft, "a") 91 | wn.onkeypress(goright, "d") 92 | 93 | segments = [] 94 | 95 | 96 | 97 | # Main Gameplay 98 | while True: 99 | wn.update() 100 | if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290: 101 | time.sleep(1) 102 | head.goto(0, 0) 103 | head.direction = "Stop" 104 | colors = random.choice(['red', 'blue', 'green']) 105 | shapes = random.choice(['square', 'circle']) 106 | for segment in segments: 107 | segment.goto(1000, 1000) 108 | segments.clear() 109 | score = 0 110 | delay = 0.1 111 | pen.clear() 112 | pen.write("Score : {} High Score : {} ".format( 113 | score, high_score), align="center", font=("candara", 24, "bold")) 114 | if head.distance(food) < 20: 115 | x = random.randint(-270, 270) 116 | y = random.randint(-270, 270) 117 | food.goto(x, y) 118 | 119 | # Adding segment 120 | new_segment = turtle.Turtle() 121 | new_segment.speed(0) 122 | new_segment.shape("square") 123 | new_segment.color("orange") # tail colour 124 | new_segment.penup() 125 | segments.append(new_segment) 126 | delay -= 0.001 127 | score += 10 128 | if score > high_score: 129 | high_score = score 130 | pen.clear() 131 | pen.write("Score : {} High Score : {} ".format( 132 | score, high_score), align="center", font=("candara", 24, "bold")) 133 | # Checking for head collisions with body segments 134 | for index in range(len(segments)-1, 0, -1): 135 | x = segments[index-1].xcor() 136 | y = segments[index-1].ycor() 137 | segments[index].goto(x, y) 138 | if len(segments) > 0: 139 | x = head.xcor() 140 | y = head.ycor() 141 | segments[0].goto(x, y) 142 | move() 143 | for segment in segments: 144 | if segment.distance(head) < 20: 145 | time.sleep(1) 146 | head.goto(0, 0) 147 | head.direction = "stop" 148 | colors = random.choice(['red', 'blue', 'green']) 149 | shapes = random.choice(['square', 'circle']) 150 | for segment in segments: 151 | segment.goto(1000, 1000) 152 | segment.clear() 153 | 154 | score = 0 155 | delay = 0.1 156 | pen.clear() 157 | pen.write("Score : {} High Score : {} ".format( 158 | score, high_score), align="center", font=("candara", 24, "bold")) 159 | time.sleep(delay) 160 | 161 | wn.mainloop() 162 | -------------------------------------------------------------------------------- /Python/tictac.py: -------------------------------------------------------------------------------- 1 | # Tic-Tac-Toe Program using 2 | # random number in Python 3 | 4 | # importing all necessary libraries 5 | import numpy as np 6 | import random 7 | from time import sleep 8 | 9 | # Creates an empty board 10 | def create_board(): 11 | return(np.array([[0, 0, 0], 12 | [0, 0, 0], 13 | [0, 0, 0]])) 14 | 15 | # Check for empty places on board 16 | def possibilities(board): 17 | l = [] 18 | 19 | for i in range(len(board)): 20 | for j in range(len(board)): 21 | 22 | if board[i][j] == 0: 23 | l.append((i, j)) 24 | return(l) 25 | 26 | # Select a random place for the player 27 | def random_place(board, player): 28 | selection = possibilities(board) 29 | current_loc = random.choice(selection) 30 | board[current_loc] = player 31 | return(board) 32 | 33 | # Checks whether the player has three 34 | # of their marks in a horizontal row 35 | def row_win(board, player): 36 | for x in range(len(board)): 37 | win = True 38 | 39 | for y in range(len(board)): 40 | if board[x, y] != player: 41 | win = False 42 | continue 43 | 44 | if win == True: 45 | return(win) 46 | return(win) 47 | 48 | # Checks whether the player has three 49 | # of their marks in a vertical row 50 | def col_win(board, player): 51 | for x in range(len(board)): 52 | win = True 53 | 54 | for y in range(len(board)): 55 | if board[y][x] != player: 56 | win = False 57 | continue 58 | 59 | if win == True: 60 | return(win) 61 | return(win) 62 | 63 | # Checks whether the player has three 64 | # of their marks in a diagonal row 65 | def diag_win(board, player): 66 | win = True 67 | y = 0 68 | for x in range(len(board)): 69 | if board[x, x] != player: 70 | win = False 71 | if win: 72 | return win 73 | win = True 74 | if win: 75 | for x in range(len(board)): 76 | y = len(board) - 1 - x 77 | if board[x, y] != player: 78 | win = False 79 | return win 80 | 81 | # Evaluates whether there is 82 | # a winner or a tie 83 | def evaluate(board): 84 | winner = 0 85 | 86 | for player in [1, 2]: 87 | if (row_win(board, player) or 88 | col_win(board,player) or 89 | diag_win(board,player)): 90 | 91 | winner = player 92 | 93 | if np.all(board != 0) and winner == 0: 94 | winner = -1 95 | return winner 96 | 97 | # Main function to start the game 98 | def play_game(): 99 | board, winner, counter = create_board(), 0, 1 100 | print(board) 101 | sleep(2) 102 | 103 | while winner == 0: 104 | for player in [1, 2]: 105 | board = random_place(board, player) 106 | print("Board after " + str(counter) + " move") 107 | print(board) 108 | sleep(2) 109 | counter += 1 110 | winner = evaluate(board) 111 | if winner != 0: 112 | break 113 | return(winner) 114 | 115 | # Driver Code 116 | print("Winner is: " + str(play_game())) 117 | -------------------------------------------------------------------------------- /Python/weightcalc.py: -------------------------------------------------------------------------------- 1 | # Python program to create a simple GUI 2 | # weight converter using Tkinter 3 | 4 | 5 | from tkinter import * 6 | 7 | 8 | # Create a GUI window 9 | window = Tk() 10 | 11 | # Function to convert weight 12 | # given in kg to grams, pounds 13 | # and ounces 14 | def from_kg(): 15 | 16 | # convert kg to gram 17 | gram = float(e2_value.get())*1000 18 | 19 | # convert kg to pound 20 | pound = float(e2_value.get())*2.20462 21 | 22 | # convert kg to ounce 23 | ounce = float(e2_value.get())*35.274 24 | 25 | # Enters the converted weight to 26 | # the text widget 27 | t1.delete("1.0", END) 28 | t1.insert(END,gram) 29 | 30 | t2.delete("1.0", END) 31 | t2.insert(END,pound) 32 | 33 | t3.delete("1.0", END) 34 | t3.insert(END,ounce) 35 | 36 | # Create the Label widgets 37 | e1 = Label(window, text = "Enter the weight in Kg") 38 | e2_value = StringVar() 39 | e2 = Entry(window, textvariable = e2_value) 40 | e3 = Label(window, text = 'Gram') 41 | e4 = Label(window, text = 'Pounds') 42 | e5 = Label(window, text = 'Ounce') 43 | 44 | # Create the Text Widgets 45 | t1 = Text(window, height = 1, width = 20) 46 | t2 = Text(window, height = 1, width = 20) 47 | t3 = Text(window, height = 1, width = 20) 48 | 49 | # Create the Button Widget 50 | b1 = Button(window, text = "Convert", command = from_kg) 51 | 52 | # grid method is used for placing 53 | # the widgets at respective positions 54 | # in table like structure 55 | e1.grid(row = 0, column = 0) 56 | e2.grid(row = 0, column = 1) 57 | e3.grid(row = 1, column = 0) 58 | e4.grid(row = 1, column = 1) 59 | e5.grid(row = 1, column = 2) 60 | t1.grid(row = 2, column = 0) 61 | t2.grid(row = 2, column = 1) 62 | t3.grid(row = 2, column = 2) 63 | b1.grid(row = 0, column = 2) 64 | 65 | # Start the GUI 66 | window.mainloop() 67 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![](https://user-images.githubusercontent.com/99328861/194718098-63ad137c-8be5-405d-bc24-17c3b8346b81.png) 2 | 3 | # python-cpp-projects 4 | This Repository is created to help fellow coders learn open source contributions. This Repository is created for Hacktoberfest 2022 5 | This repository aims to help code beginners with their first successful pull request and open source contribution. 🥳 6 | ⭐ Feel free to use this project to make your first contribution to an open-source project on GitHub. Practice making your first pull request to a public repository before doing the real thing! 7 | 8 | ### Try to work on different and unique projects which are not present in this repository already and give little description about your project. 9 | 10 | ⭐ Make sure to grab some cool swags during Hacktoberfest by getting involved in the open-source community. 11 | 12 | This repository is open to all members of the GitHub community. Any member can contribute to this project! 13 | 14 | What is Hacktoberfest? 🤔 15 | A month-long celebration from October 1st to October 31st presented by Digital Ocean and DEV Community collaborated with GitHub to get people involved in Open Source. Create your very first pull request to any public repository on GitHub and contribute to the open-source developer community. 16 | 17 | https://hacktoberfest.digitalocean.com/ 18 | 19 | Rules: 20 | 21 | To qualify for the official limited edition Hacktoberfest shirt, you must register [here](https://hacktoberfest.com/) and make four Pull Requests (PRs) between October 1-31, 2022 (in any time zone). PRs can be made to any public repository on GitHub, not only the ones with issues labeled Hacktoberfest. This year, the first 40,000 participants who complete Hacktoberfest can elect to receive one of two prizes: a tree planted in their name, or the Hacktoberfest 2022 t-shirt. 22 | 23 | ## Steps to follow :scroll: 24 | 25 | ### Tip : Complete this process in GitHub (in your browser) 26 | 27 | ```mermaid 28 | flowchart LR 29 | Fork[Fork the project] 30 | -->Edit[Edit file] 31 | -->commit -->|Finally|creatpr((Create a Pull Request)) 32 | 33 | ``` 34 | 35 | ### 1. Fork it :fork_and_knife: 36 | 37 | You can get your own fork/copy of [HacktoberFest-2022](https://github.com/anomekumar08/python-cpp-projects) by using the Fork button. 38 | 39 | ### 2. Clone it :busts_in_silhouette: 40 | 41 | `NOTE: commands are to be executed on Linux, Mac, and Windows(using Powershell or git bash)` 42 | 43 | You need to clone or (download) it to local machine using 44 | 45 | ```sh 46 | $ git clone https://github.com/Your_Username/Hacktoberfest-2022.git 47 | ``` 48 | 49 | ### 3. Make file change and commit: 50 | 51 | Now, open the directory in which you cloned it and add your project or make any changes that you want.Then,commit it and push into your created repository. 52 | 53 | ### 4. Pull request: 54 | 55 | Then you need to go into your repository and click on "Contribute" --> "Open Pull Request". 56 | 57 | ### So, you have successfully made your pull request.Now, I will verify your pull request and merge it into my repository. 58 | --------------------------------------------------------------------------------